Add two numbers represented by Stacks | 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
function addStack ( N1 , N2 ) { var res = [ ] ; var sum = 0 , rem = 0 ; while ( N1 . length != 0 && N2 . length != 0 ) { sum = ( rem + N1 [ N1 . length - 1 ] + N2 [ N2 . length - 1 ] ) ; res . push ( sum % 10 ) ; rem = parseInt ( sum / 10 ) ; N1 . pop ( ) ; N2 . pop ( ) ; } while ( N1 . length != 0 ) { sum = ( rem + N1 [ N1 . length - 1 ] ) ; res . push ( sum % 10 ) ; rem = parseInt ( sum / 10 ) ; N1 . pop ( ) ; } while ( N2 . length != 0 ) { sum = ( rem + N2 [ N2 . length - 1 ] ) ; res . push ( sum % 10 ) ; rem = parseInt ( sum / 10 ) ; N2 . pop ( ) ; } while ( rem > 0 ) { res . push ( rem ) ; rem = parseInt ( rem / 10 ) ; } while ( res . length != 0 ) { N1 . push ( res [ res . length - 1 ] ) ; res . pop ( ) ; } res = N1 ; return res ; } function display ( res ) { var N = res . length ; var s = " " ; while ( res . length != 0 ) { s = ( res [ res . length - 1 ] . toString ( ) ) + s ; res . pop ( ) ; } document . write ( s ) ; } var N1 = [ ] ; N1 . push ( 5 ) ; N1 . push ( 8 ) ; N1 . push ( 7 ) ; N1 . push ( 4 ) ; var N2 = [ ] ; N2 . push ( 2 ) ; N2 . push ( 1 ) ; N2 . push ( 3 ) ; var res = addStack ( N1 , N2 ) ; display ( res ) ;