150. Evaluate Reverse Polish Notation#
1public int evalRPN(String[] tokens) {
2 Stack<Integer> stk = new Stack<>();
3
4 for (String token : tokens) {
5 if (token.equals("+")) {
6 int b = stk.pop();
7 int a = stk.pop();
8
9 stk.push(a + b);
10 } else if (token.equals("-")) {
11 int b = stk.pop();
12 int a = stk.pop();
13
14 stk.push(a - b);
15 } else if (token.equals("*")) {
16 int b = stk.pop();
17 int a = stk.pop();
18
19 stk.push(a * b);
20 } else if (token.equals("/")) {
21 int b = stk.pop();
22 int a = stk.pop();
23
24 stk.push(a / b);
25 } else {
26 stk.push(Integer.parseInt(token));
27 }
28 }
29
30 return stk.pop();
31}