Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +
, -
, *
, /
. Each operand may be an integer or another expression.
Some examples:
["2", "1", "+", "3", "*"] -> ((2 + 1) * 3) -> 9 ["4", "13", "5", "/", "+"] -> (4 + (13 / 5)) -> 6
public class Solution { public int evalRPN(String[] tokens) { int value = 0; String operations ="+-*/"; Stack<String> stack = new Stack<String>(); for(String s:tokens){ if(!operations.contains(s)){ stack.push(s); } else{ Integer a = Integer.valueOf(stack.pop()); Integer b = Integer.valueOf(stack.pop()); int index = operations.indexOf(s); switch(index){ case 0: stack.push(String.valueOf(a+b)); break; case 1: stack.push(String.valueOf(b-a)); break; case 2: stack.push(String.valueOf(a*b)); break; case 3: stack.push(String.valueOf(b/a)); break; } } } value = Integer.valueOf(stack.pop()); return value; } }
learned: Integer.valueOf(stack.pop()) = Integer.parseInt(stack.pop());