Concatenate the answer with smaller value of the topmost elements of both the stacks and then pop that element
if ( stack1 [ stack1 . length - 1 ] < stack2 [ stack2 . length - 1 ] ) { ans = ans * 10 + stack1 [ stack1 . length - 1 ] ; stack1 . pop ( ) ; } else { ans = ans * 10 + stack2 [ stack2 . length - 1 ] ; stack2 . pop ( ) ; } }