Add two numbers represented by Stacks | C ++ program to implement the above approach ; Function to return the stack that contains the sum of two numbers ; Calculate the sum of the top elements of both the stacks ; Push the sum into the stack ; Store the carry ; Pop the top elements ; If N1 is not empty ; If N2 is not empty ; If carry remains ; Reverse the stack . so that most significant digit is at the bottom of the stack ; Function to display the resultamt stack ; Driver Code
#include <bits/stdc++.h> NEW_LINE using namespace std ; stack < int > addStack ( stack < int > N1 , stack < int > N2 ) { stack < int > res ; int sum = 0 , rem = 0 ; while ( ! N1 . empty ( ) and ! N2 . empty ( ) ) { sum = ( rem + N1 . top ( ) + N2 . top ( ) ) ; res . push ( sum % 10 ) ; rem = sum / 10 ; N1 . pop ( ) ; N2 . pop ( ) ; } while ( ! N1 . empty ( ) ) { sum = ( rem + N1 . top ( ) ) ; res . push ( sum % 10 ) ; rem = sum / 10 ; N1 . pop ( ) ; } while ( ! N2 . empty ( ) ) { sum = ( rem + N2 . top ( ) ) ; res . push ( sum % 10 ) ; rem = sum / 10 ; N2 . pop ( ) ; } while ( rem > 0 ) { res . push ( rem ) ; rem /= 10 ; } while ( ! res . empty ( ) ) { N1 . push ( res . top ( ) ) ; res . pop ( ) ; } res = N1 ; return res ; } void display ( stack < int > & res ) { int N = res . size ( ) ; string s = " " ; while ( ! res . empty ( ) ) { s = to_string ( res . top ( ) ) + s ; res . pop ( ) ; } cout << s << endl ; } int main ( ) { stack < int > N1 ; N1 . push ( 5 ) ; N1 . push ( 8 ) ; N1 . push ( 7 ) ; N1 . push ( 4 ) ; stack < int > N2 ; N2 . push ( 2 ) ; N2 . push ( 1 ) ; N2 . push ( 3 ) ; stack < int > res = addStack ( N1 , N2 ) ; display ( res ) ; return 0 ; }