Search code examples
javasubtraction

Reverse Polish Notation Calc: subtraction of two positive numbers returning a minus?


When performing a subtraction of two number on my Reverse Polish Notation Calculator, I get a minus number result, for example:

20 5 - = -15

Whereas, I would expect to see 15.

Can anyone see where I am going wrong with my code?

   else if (input.equals("-")) {
            int n1 = stack.pop();
            int n2 = stack.pop();
            int result = n1 - n2;

            stack.push((int)result);
        }

Solution

  • The principle of a stack is LIFO (Last In First Out).

    Therefore, when you first push 20 and then push 5 into the stack, the first pop will return 5 and the second pop will return 20. Therefore you calculate 5 - 20 instead of 20 - 5.

    You should reverse the order of the operands in order to make the correct computation:

    else if (input.equals("-")) {
        int n1 = stack.pop();
        int n2 = stack.pop();
        int result = n2 - n1;
        stack.push((int)result);
    }