Add two numbers represented by Stacks | Java 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
import java . util . Stack ; class GFG { static Stack < Integer > addStack ( Stack < Integer > N1 , Stack < Integer > N2 ) { Stack < Integer > res = new Stack < Integer > ( ) ; int sum = 0 , rem = 0 ; while ( ! N1 . isEmpty ( ) && ! N2 . isEmpty ( ) ) { sum = ( rem + N1 . peek ( ) + N2 . peek ( ) ) ; res . add ( sum % 10 ) ; rem = sum / 10 ; N1 . pop ( ) ; N2 . pop ( ) ; } while ( ! N1 . isEmpty ( ) ) { sum = ( rem + N1 . peek ( ) ) ; res . add ( sum % 10 ) ; rem = sum / 10 ; N1 . pop ( ) ; } while ( ! N2 . isEmpty ( ) ) { sum = ( rem + N2 . peek ( ) ) ; res . add ( sum % 10 ) ; rem = sum / 10 ; N2 . pop ( ) ; } while ( rem > 0 ) { res . add ( rem ) ; rem /= 10 ; } while ( ! res . isEmpty ( ) ) { N1 . add ( res . peek ( ) ) ; res . pop ( ) ; } res = N1 ; return res ; } static void display ( Stack < Integer > res ) { int N = res . size ( ) ; String s = " " ; while ( ! res . isEmpty ( ) ) { s = String . valueOf ( res . peek ( ) ) + s ; res . pop ( ) ; } System . out . print ( s + "NEW_LINE"); } public static void main ( String [ ] args ) { Stack < Integer > N1 = new Stack < Integer > ( ) ; N1 . add ( 5 ) ; N1 . add ( 8 ) ; N1 . add ( 7 ) ; N1 . add ( 4 ) ; Stack < Integer > N2 = new Stack < Integer > ( ) ; N2 . add ( 2 ) ; N2 . add ( 1 ) ; N2 . add ( 3 ) ; Stack < Integer > res = addStack ( N1 , N2 ) ; display ( res ) ; } }