Sum of two large numbers | Function for finding sum of larger numbers ; Before proceeding further , make sure length of str2 is larger . ; Take an empty string for storing result ; Calculate length of both string ; Initially take carry zero ; Traverse from end of both strings ; Do school mathematics , compute sum of current digits and carry ; Add remaining digits of str2 [ ] ; Add remaining carry ; reverse resultant string ; Driver code
def findSum ( str1 , str2 ) : NEW_LINE INDENT if len ( str1 ) > len ( str2 ) : NEW_LINE INDENT temp = str1 NEW_LINE str1 = str2 NEW_LINE str2 = temp NEW_LINE DEDENT str3 = " " NEW_LINE n1 = len ( str1 ) NEW_LINE n2 = len ( str2 ) NEW_LINE diff = n2 - n1 NEW_LINE carry = 0 NEW_LINE for i in range ( n1 - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum = ( ( ord ( str1 [ i ] ) - ord ( '0' ) ) + int ( ( ord ( str2 [ i + diff ] ) - ord ( '0' ) ) ) + carry ) NEW_LINE str3 = str3 + str ( sum % 10 ) NEW_LINE carry = sum // 10 NEW_LINE DEDENT for i in range ( n2 - n1 - 1 , - 1 , - 1 ) : NEW_LINE INDENT sum = ( ( ord ( str2 [ i ] ) - ord ( '0' ) ) + carry ) NEW_LINE str3 = str3 + str ( sum % 10 ) NEW_LINE carry = sum // 10 NEW_LINE DEDENT if ( carry ) : NEW_LINE INDENT str3 + str ( carry + '0' ) NEW_LINE DEDENT str3 = str3 [ : : - 1 ] NEW_LINE return str3 NEW_LINE DEDENT if __name__ == " _ _ main _ _ " : NEW_LINE INDENT str1 = "12" NEW_LINE str2 = "198111" NEW_LINE print ( findSum ( str1 , str2 ) ) NEW_LINE DEDENT