加减乘除

Evaluate Reverse Polish Notation

  • RPN 是典型的Stack应用题,Calculator的pre-requisite

public int evalRPN(String[] tokens) {
        Stack<Integer> stk = new Stack<>();
        String operators = "+-*/";
        for(String token : tokens) {
            if (! operators.contains(token)) {
                stk.push(Integer.parseInt(token));
            } else {
                int num2 = stk.pop();
                int num1 = stk.pop();
                int res = 0;
                switch (token) {
                    case "+":
                        res = num1 + num2;
                        break;
                    case "-":
                        res = num1 - num2;
                        break;
                    case "/":
                        res = num1 / num2;
                        break;
                    case "*":
                        res = num1 * num2;
                        break;   
                }
                stk.push(res);
            }
        }
        return stk.pop();
    }

Pow(x, n)

  • 如果n < 0, 就x = 1/ x, n = -n

  • 注意-n 可能会integer overflow

Last updated

Was this helpful?