加减乘除
Evaluate Reverse Polish Notation
public int evalRPN(String[] tokens) {
Stack<Integer> stk = new Stack<>();
String operators = "+-*/";
for(String token : tokens) {
if (! operators.contains(token)) {
stk.push(Integer.parseInt(token));
} else {
int num2 = stk.pop();
int num1 = stk.pop();
int res = 0;
switch (token) {
case "+":
res = num1 + num2;
break;
case "-":
res = num1 - num2;
break;
case "/":
res = num1 / num2;
break;
case "*":
res = num1 * num2;
break;
}
stk.push(res);
}
}
return stk.pop();
}Pow(x, n)
Last updated