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
def addStack ( N1 , N2 ) : NEW_LINE INDENT res = [ ] NEW_LINE s = 0 NEW_LINE rem = 0 NEW_LINE while ( len ( N1 ) != 0 and len ( N2 ) != 0 ) : NEW_LINE INDENT s = ( rem + N1 [ - 1 ] + N2 [ - 1 ] ) NEW_LINE res . append ( s % 10 ) NEW_LINE rem = s // 10 NEW_LINE N1 . pop ( - 1 ) NEW_LINE N2 . pop ( - 1 ) NEW_LINE DEDENT while ( len ( N1 ) != 0 ) : NEW_LINE INDENT s = rem + N1 [ - 1 ] NEW_LINE res . append ( s % 10 ) NEW_LINE rem = s // 10 NEW_LINE N1 . pop ( - 1 ) NEW_LINE DEDENT while ( len ( N2 ) != 0 ) : NEW_LINE INDENT s = rem + N2 [ - 1 ] NEW_LINE res . append ( s % 10 ) NEW_LINE rem = s // 10 NEW_LINE N2 . pop ( - 1 ) NEW_LINE DEDENT while ( rem > 0 ) : NEW_LINE INDENT res . append ( rem ) NEW_LINE rem //= 10 NEW_LINE DEDENT res = res [ : : - 1 ] NEW_LINE return res NEW_LINE DEDENT def display ( res ) : NEW_LINE INDENT s = " " NEW_LINE for i in res : NEW_LINE INDENT s += str ( i ) NEW_LINE DEDENT print ( s ) NEW_LINE DEDENT N1 = [ ] NEW_LINE N1 . append ( 5 ) NEW_LINE N1 . append ( 8 ) NEW_LINE N1 . append ( 7 ) NEW_LINE N1 . append ( 4 ) NEW_LINE N2 = [ ] NEW_LINE N2 . append ( 2 ) NEW_LINE N2 . append ( 1 ) NEW_LINE N2 . append ( 3 ) NEW_LINE res = addStack ( N1 , N2 ) NEW_LINE display ( res ) NEW_LINE