Evaluate Reverse Polish Notation

Evaluate the value of an arithmetic expression in Reverse Polish Notation.

Valid operators are +, -, *, /. Each operand may be an integer or another expression.

Some examples:

["2", "1", "+", "3", ""] -> ((2 + 1) 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6

Solution

public class Solution {
 public int evalRPN(String[] tokens) {
        Stack<String> stack = new Stack<>();

        for(String s:tokens) {
            switch (s) {
                case "+":
                case "-":
                case "*":
                case "/":
                    int a = Integer.valueOf(stack.pop());
                    int b = Integer.valueOf(stack.pop());

                    int c = a+b;
                    if (s.equals("-")) {
                        c = b - a;
                    } else if (s.equals("*")) {
                        c = a*b;
                    } else if (s.equals("/")) {
                        c = b / a;
                    }

                    stack.push(String.valueOf(c));

                    break;

                default:
                    stack.push(s);
                    break;
            }
        }

        return Integer.valueOf(stack.pop());
    }
}

results matching ""

    No results matching ""