Problem
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Example
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9
["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
Note
Switch中的运算符case,运算之后要break出来,继续遍历tokens数组。
default是放入新的数字,用parseInt()/valueOf()转换String为Integer均可。
Solution
public class Solution {
public int evalRPN(String[] tokens) {
if (tokens == null || tokens.length % 2 == 0) return 0;
Stack<Integer> stack = new Stack<Integer>();
for (String tok: tokens) {
switch(tok) {
case "+":
stack.push(stack.pop() + stack.pop());
break;
case "-":
stack.push(-stack.pop() + stack.pop());
break;
case "*":
stack.push(stack.pop() * stack.pop());
break;
case "/":
int divisor = stack.pop();
int dividend = stack.pop();
stack.push(dividend/divisor);
break;
default:
stack.push(Integer.valueOf(tok));
}
}
return stack.pop();
}
}
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。