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