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
思路:将数字放到栈里面,遇到符号就将最上面的两个数弹栈并进行运算,注意两个数的先后顺序
代码:
import java.util.Stack;
public class Solution {
public int evalRPN(String[] tokens) {
int i=0;
Stack<Integer> stack=new Stack();
while (i<tokens.length){
if (tokens[i].equals("+")){
int n=stack.pop();
int m=stack.pop();
stack.push(n+m);
}
else if (tokens[i].equals("-")){
int n=stack.pop();
int m=stack.pop();
stack.push(m-n);
}
else if (tokens[i].equals("*")){
int n=stack.pop();
int m=stack.pop();
stack.push(n*m);
}
else if (tokens[i].equals("/")){
int n=stack.pop();
int m=stack.pop();
if (n==0)return 0;
stack.push(m/n);
}else {
stack.push(Integer.parseInt(tokens[i]));
}
i++;
}
return stack.pop();
}
}