|
| 1 | +import java.util.Stack; |
| 2 | + |
| 3 | +/** |
| 4 | + * Evaluate the value of an arithmetic expression in Reverse Polish Notation. |
| 5 | + * Valid operators are +, -, *, /. Each operand may be an integer or another expression. |
| 6 | + * <p> |
| 7 | + * Some examples: |
| 8 | + * ["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 |
| 9 | + * ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6 |
| 10 | + * <p> |
| 11 | + * Created by drfish on 6/8/2017. |
| 12 | + */ |
| 13 | +public class _150EvaluateReversePolishNotation { |
| 14 | + public int evalRPN(String[] tokens) { |
| 15 | + if (tokens == null) { |
| 16 | + return 0; |
| 17 | + } |
| 18 | + Stack<Integer> stack = new Stack<>(); |
| 19 | + for (String token : tokens) { |
| 20 | + switch (token) { |
| 21 | + case "+": |
| 22 | + stack.push(stack.pop() + stack.pop()); |
| 23 | + break; |
| 24 | + case "*": |
| 25 | + stack.push(stack.pop() * stack.pop()); |
| 26 | + break; |
| 27 | + case "-": |
| 28 | + int second = stack.pop(); |
| 29 | + int first = stack.pop(); |
| 30 | + stack.push(first - second); |
| 31 | + break; |
| 32 | + case "/": |
| 33 | + second = stack.pop(); |
| 34 | + first = stack.pop(); |
| 35 | + stack.push(first / second); |
| 36 | + break; |
| 37 | + default: |
| 38 | + stack.push(Integer.valueOf(token)); |
| 39 | + } |
| 40 | + } |
| 41 | + return stack.pop(); |
| 42 | + } |
| 43 | + |
| 44 | + public static void main(String[] args) { |
| 45 | + _150EvaluateReversePolishNotation solution = new _150EvaluateReversePolishNotation(); |
| 46 | + assert 9 == solution.evalRPN(new String[]{"2", "1", "+", "3", "*"}); |
| 47 | + assert 6 == solution.evalRPN(new String[]{"4", "13", "5", "/", "+"}); |
| 48 | + } |
| 49 | +} |
0 commit comments