Question:
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
Thinking:
We should use stack and scan the elements of this string array. Whenever we get the operator, we pop element from the stack and push new element to the stack.
Solutioin:
public int evalRPN(String[] tokens) {
Stack<Integer> stack = new Stack<Integer>();
for (String s: tokens) {
if (s.equals("+")) {
int num1 = stack.pop();
int num2 = stack.pop();
stack.push(num1+num2);
}
else if (s.equals("-")) {
int num1 = stack.pop();
int num2 = stack.pop();
stack.push(num2-num1);
}
else if (s.equals("*")) {
int num1 = stack.pop();
int num2 = stack.pop();
stack.push(num1*num2);
}
else if (s.equals("/")) {
int num1 = stack.pop();
int num2 = stack.pop();
stack.push(num2/num1);
}
else
stack.push(Integer.parseInt(s));
}
return stack.pop();
}