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
用了stack,遍历数组,遇到数字就push,遇到运算符,取出stack中最近入栈的两个数进行计算,然后继续入栈。
最后return stack中的结果即可
public int evalRPN(String[] tokens) {
if(tokens.length==0)
return 0;
Stack<String> stack = new Stack<String>();
int result =0;
for(int i=0; i<tokens.length; i++){
if(tokens[i].equals("*")||tokens[i].equals("/")||tokens[i].equals("+")||tokens[i].equals("-")){
int tmp = calculate(tokens[i], stack);
stack.push(String.valueOf(tmp));
}
else
stack.push(tokens[i]);
}
return Integer.parseInt(stack.pop());
}
public int calculate(String op, Stack<String> stack){
int num2 = Integer.parseInt(stack.pop());
int num1 = Integer.parseInt(stack.pop());
if(op.equals("*")) return num1*num2;
else if(op.equals("/") )return num1/num2;
else if(op.equals("+")) return num1+num2;
else return num1-num2;
}