Sum of two large numbers | C ++ program to find 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
#include <bits/stdc++.h> NEW_LINE using namespace std ; string findSum ( string str1 , string str2 ) { if ( str1 . length ( ) > str2 . length ( ) ) swap ( str1 , str2 ) ; string str = " " ; int n1 = str1 . length ( ) , n2 = str2 . length ( ) ; int diff = n2 - n1 ; int carry = 0 ; for ( int i = n1 - 1 ; i >= 0 ; i -- ) { int sum = ( ( str1 [ i ] - '0' ) + ( str2 [ i + diff ] - '0' ) + carry ) ; str . push_back ( sum % 10 + '0' ) ; carry = sum / 10 ; } for ( int i = n2 - n1 - 1 ; i >= 0 ; i -- ) { int sum = ( ( str2 [ i ] - '0' ) + carry ) ; str . push_back ( sum % 10 + '0' ) ; carry = sum / 10 ; } if ( carry ) str . push_back ( carry + '0' ) ; reverse ( str . begin ( ) , str . end ( ) ) ; return str ; } int main ( ) { string str1 = "12" ; string str2 = "198111" ; cout << findSum ( str1 , str2 ) ; return 0 ; }