| 1 | class Solution { |
| 2 | |
| 3 | public int evalRPN(String[] tokens) { |
| 4 | Stack<Integer> stack = new Stack<>(); |
| 5 | for (String token : tokens) { |
| 6 | if (token.equals("+")) { |
| 7 | stack.add(stack.pop() + stack.pop()); |
| 8 | } else if (token.equals("-")) { |
| 9 | int a = stack.pop(); |
| 10 | int b = stack.pop(); |
| 11 | stack.add(b - a); |
| 12 | } else if (token.equals("*")) { |
| 13 | stack.add(stack.pop() * stack.pop()); |
| 14 | } else if (token.equals("/")) { |
| 15 | int a = stack.pop(); |
| 16 | int b = stack.pop(); |
| 17 | stack.add(b / a); |
| 18 | } else { |
| 19 | stack.add(Integer.parseInt(token)); |
| 20 | } |
| 21 | } |
| 22 | return stack.pop(); |
| 23 | } |
| 24 | } |