LeetCode—150. Evaluate Reverse Polish Notation

LeetCode—150. Evaluate Reverse Polish Notation

题目

https://leetcode.com/problems/evaluate-reverse-polish-notation/description/
计算给出波兰式的计算结果。不同于一般的数学算式,波兰式改变了运算符和运算数字的顺序,具体的看一眼例子就可以明白了。
LeetCode—150. Evaluate Reverse Polish Notation

思路及解法

观察波兰式的写法,很容易发现是如何操作的,对于每一个运算符,取他前面的两个运算数字进行运算,并且将计算结果放回到原顺序位置。考虑用栈实现。

代码

class Solution {
    public int evalRPN(String[] tokens) {
        int len = tokens.length;
        Stack<Integer> stack = new Stack<>();
        for(int i=0; i<len; i++){
            if(tokens[i].equals("+")){
                stack.push(stack.pop()+stack.pop());
            }else if(tokens[i].equals("-")){
                stack.push((0-stack.pop())+stack.pop());
            }else if(tokens[i].equals("*")){
                stack.push(stack.pop()*stack.pop());
            }else if(tokens[i].equals("/")){
                int a = stack.pop();
                int b = stack.pop();
                int temp = b / a;
                stack.push(temp);
                // stack.push((1/stack.pop())*stack.pop()); //这样写是会报可能为零 的错误的,不明白是怎么回事。。
            }else{
                stack.push(Integer.parseInt(tokens[i]));
            }
        }
        return stack.pop();
      
    }
}