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 rst = 0;
Stack<String> stack = new Stack<String>();
for(String s : tokens) {
if("+".equals(s)) {
int a = Integer.parseInt(stack.pop()), b = Integer.parseInt(stack.pop());
rst = a + b;
stack.push(rst + "");
} else if("-".equals(s)) {
int a = Integer.parseInt(stack.pop()), b = Integer.parseInt(stack.pop());
rst = b - a;
stack.push(rst + "");
} else if("*".equals(s)) {
int a = Integer.parseInt(stack.pop()), b = Integer.parseInt(stack.pop());
rst = a * b;
stack.push(rst + "");
} else if("/".equals(s)) {
int a = Integer.parseInt(stack.pop()), b = Integer.parseInt(stack.pop());
rst = b / a;
stack.push(rst + "");
} else {
rst = Integer.parseInt(s);
stack.push(s);
}
}
return rst;
}
}