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
My code:
public class Solution {
public int evalRPN(String[] tokens) {
Stack<String> stack = new Stack<>();
for(String str:tokens){
if(str.equals("+")||str.equals("-")||str.equals("*")||str.equals("/")){
int op2 = stack.pop();
int op1 = stack.pop();
if(op.equals('+')) stack.push(op1+op2);
else if (op.equals('-')) stack.push(op1-op2);
else if (op.equals('*')) stack.push(op1*op2);
else stack.push(op1/op2);
}
else{
stack.push(Integer.parseInt(str));
}
}
}
}
怎么就不对呢