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
Use a stack.
public class Solution {
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<>();
for (String token: tokens) {
if (isOperator(token)) {
stack.push(compute(token, stack.pop(), stack.pop()));
} else {
stack.push(Integer.valueOf(token));
}
}
return stack.pop();
}
private boolean isOperator(String token) {
if (token.equals("+") || token.equals("-")
|| token.equals("*") || token.equals("/")) {
return true;
}
return false;
}
private int compute(String operator, int num2, int num1) {
int result = 0;
switch (operator.charAt(0)) {
case '+': result = num1 + num2; break;
case '-': result = num1 - num2; break;
case '*': result = num1 * num2; break;
case '/': result = num1 / num2; break;
}
return result;
}
}