LeetCode 3

832 查看

Evaluate Reverse Polish Notation https://oj.leetcode.com/problems/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

这个题没什么好说的,用栈就可以了,注意一下两个数计算的时候谁前谁后就行了。

public int evalRPN(String[] tokens) {
        Stack<String> stack = new Stack<String>();
        int num1 = 0;
        int num2 = 0;
        for(int i = 0; i < tokens.length; i++){
            if (tokens[i].equals("+")){
                //calcuate
                num1 = Integer.parseInt(stack.pop());
                num2 = Integer.parseInt(stack.pop());
                stack.push(String.format("%s", num2+num1));
            }else if(tokens[i].equals("-")){
                num1 = Integer.parseInt(stack.pop());
                num2 = Integer.parseInt(stack.pop());
                stack.push(String.format("%s", num2-num1));
            }else if(tokens[i].equals("*")){
                num1 = Integer.parseInt(stack.pop());
                num2 = Integer.parseInt(stack.pop());
                stack.push(String.format("%s", num2*num1));
            }else if(tokens[i].equals("/")){
                num1 = Integer.parseInt(stack.pop());
                num2 = Integer.parseInt(stack.pop());
                stack.push(String.format("%s", num2/num1));
            }else{
                //push to stack
                stack.push(tokens[i]);
            }
        }
        return Integer.parseInt(stack.peek());      
    }