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
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
public class Solution {
public int evalRPN(String[] tokens) {
if (tokens == null || tokens.length < 1) {
return 0;
}
Stack<Integer> numStack = new Stack<Integer>();
for (int i = 0; i < tokens.length; i++) {
String nowStr = tokens[i];
// 注意除法和减法的操作数先后顺序
if ("+".equals(nowStr)) {
int num1 = numStack.pop();
int num2 = numStack.pop();
int rs = num1 + num2;
numStack.push(rs);
} else if ("-".equals(nowStr)) {
int num1 = numStack.pop();
int num2 = numStack.pop();
int rs = num2 - num1;
numStack.push(rs);
} else if ("*".equals(nowStr)) {
int num1 = numStack.pop();
int num2 = numStack.pop();
int rs = num1 * num2;
numStack.push(rs);
} else if ("/".equals(nowStr)) {
int num1 = numStack.pop();
int num2 = numStack.pop();
int rs = num2 / num1;
numStack.push(rs);
} else {
numStack.push(Integer.parseInt(nowStr));
}
}
return numStack.pop();
}
}