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 ; Reverse both of strings ; Do school mathematics , compute sum of current digits and carry ; Calculate carry for next step ; Add remaining digits of larger number ; Add remaining carry ; reverse resultant string ; Driver code
def findSum ( str1 , str2 ) : NEW_LINE INDENT if ( len ( str1 ) > len ( str2 ) ) : NEW_LINE INDENT t = str1 ; NEW_LINE str1 = str2 ; NEW_LINE str2 = t ; NEW_LINE DEDENT str = " " ; NEW_LINE n1 = len ( str1 ) ; NEW_LINE n2 = len ( str2 ) ; NEW_LINE str1 = str1 [ : : - 1 ] ; NEW_LINE str2 = str2 [ : : - 1 ] ; NEW_LINE carry = 0 ; NEW_LINE for i in range ( n1 ) : NEW_LINE INDENT sum = ( ( ord ( str1 [ i ] ) - 48 ) + ( ( ord ( str2 [ i ] ) - 48 ) + carry ) ) ; NEW_LINE str += chr ( sum % 10 + 48 ) ; NEW_LINE carry = int ( sum / 10 ) ; NEW_LINE DEDENT for i in range ( n1 , n2 ) : NEW_LINE INDENT sum = ( ( ord ( str2 [ i ] ) - 48 ) + carry ) ; NEW_LINE str += chr ( sum % 10 + 48 ) ; NEW_LINE carry = ( int ) ( sum / 10 ) ; NEW_LINE DEDENT if ( carry ) : NEW_LINE INDENT str += chr ( carry + 48 ) ; NEW_LINE DEDENT str = str [ : : - 1 ] ; NEW_LINE return str ; NEW_LINE DEDENT str1 = "12" ; NEW_LINE str2 = "198111" ; NEW_LINE print ( findSum ( str1 , str2 ) ) ; NEW_LINE