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
function findSum ( str1 , str2 ) { if ( str1 . length > str2 . length ) { let t = str1 ; str1 = str2 ; str2 = t ; } let str = " " ; let n1 = str1 . length , n2 = str2 . length ; str1 = str1 . split ( " " ) . reverse ( ) . join ( " " ) ; str2 = str2 . split ( " " ) . reverse ( ) . join ( " " ) ; let carry = 0 ; for ( let i = 0 ; i < n1 ; i ++ ) { let sum = ( ( str1 [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) + ( str2 [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) + carry ) ; str += String . fromCharCode ( sum % 10 + ' ' . charCodeAt ( 0 ) ) ; carry = Math . floor ( sum / 10 ) ; } for ( let i = n1 ; i < n2 ; i ++ ) { let sum = ( ( str2 [ i ] . charCodeAt ( 0 ) - ' ' . charCodeAt ( 0 ) ) + carry ) ; str += String . fromCharCode ( sum % 10 + ' ' . charCodeAt ( 0 ) ) ; carry = Math . floor ( sum / 10 ) ; } if ( carry > 0 ) str += String . fromCharCode ( carry + ' ' . charCodeAt ( 0 ) ) ; str = str . split ( " " ) . reverse ( ) . join ( " " ) ; return str ; } let str1 = " " ; let str2 = " " ; document . write ( findSum ( str1 , str2 ) )