题目描述
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) {
Stack<Integer> stack = new Stack<Integer>();
int topB, topA;
for (int i=0; i<tokens.length; ++i) {
if ("+".equals(tokens[i])) {
topB = stack.pop();
topA = stack.pop();
stack.add(topA+topB);
} else if ("-".equals(tokens[i])) {
topB = stack.pop();
topA = stack.pop();
stack.add(topA-topB);
} else if ("*".equals(tokens[i])) {
topB = stack.pop();
topA = stack.pop();
stack.add(topA*topB);
} else if ("/".equals(tokens[i])) {
topB = stack.pop();
topA = stack.pop();
stack.add(topA/topB);
} else {
stack.add(Integer.parseInt(tokens[i]));
}
}
return stack.peek();
}
}