Open huimeich opened 8 years ago
public class Solution {
public int evalRPN(String[] tokens) {
int res = 0;
Stack<Integer> stack = new Stack<Integer>();
for (String op : tokens){
int opNum;
if (op.equals("+")){
res = stack.pop();
res += stack.pop();
stack.push(res);
} else if (op.equals("-")){
res = stack.pop();
res = stack.pop() - res;
stack.push(res);
}else if (op.equals("*")){
res = stack.pop();
res *= stack.pop();
stack.push(res);
}else if (op.equals("/")){
res = stack.pop();
res = stack.pop() / res;
stack.push(res);
}else {
stack.push(Integer.valueOf(op));
}
}
return stack.pop();
}
}
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