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
using System ; using System . Collections . Generic ; class GFG { static Stack < int > PushStack ( Stack < int > N1 , Stack < int > N2 ) { Stack < int > res = new Stack < int > ( ) ; int sum = 0 , rem = 0 ; while ( N1 . Count != 0 && N2 . Count != 0 ) { sum = ( rem + N1 . Peek ( ) + N2 . Peek ( ) ) ; res . Push ( ( int ) sum % 10 ) ; rem = sum / 10 ; N1 . Pop ( ) ; N2 . Pop ( ) ; } while ( N1 . Count != 0 ) { sum = ( rem + N1 . Peek ( ) ) ; res . Push ( sum % 10 ) ; rem = sum / 10 ; N1 . Pop ( ) ; } while ( N2 . Count != 0 ) { sum = ( rem + N2 . Peek ( ) ) ; res . Push ( sum % 10 ) ; rem = sum / 10 ; N2 . Pop ( ) ; } while ( rem > 0 ) { res . Push ( rem ) ; rem /= 10 ; } while ( res . Count != 0 ) { N1 . Push ( res . Peek ( ) ) ; res . Pop ( ) ; } res = N1 ; return res ; } static void display ( Stack < int > res ) { int N = res . Count ; String s = " " ; while ( res . Count != 0 ) { s = String . Join ( " " , res . Peek ( ) ) + s ; res . Pop ( ) ; } Console . Write ( s + " STRNEWLINE " ) ; } public static void Main ( String [ ] args ) { Stack < int > N1 = new Stack < int > ( ) ; N1 . Push ( 5 ) ; N1 . Push ( 8 ) ; N1 . Push ( 7 ) ; N1 . Push ( 4 ) ; Stack < int > N2 = new Stack < int > ( ) ; N2 . Push ( 2 ) ; N2 . Push ( 1 ) ; N2 . Push ( 3 ) ; Stack < int > res = PushStack ( N1 , N2 ) ; display ( res ) ; } }