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
Easy one
public class Solution { public int evalRPN(String[] tokens) { Stack<Integer> stack = new Stack<Integer>(); int result = 0; for (String s : tokens) { if (s.equals("+")) { result = stack.pop() + stack.pop(); stack.push(result); } else if (s.equals("-")) { result = -stack.pop() + stack.pop(); stack.push(result); } else if (s.equals("*")) { result = stack.pop() * stack.pop(); stack.push(result); } else if (s.equals("/")) { int a = stack.pop(); result = stack.pop()/a; stack.push(result); } else { stack.push(Integer.parseInt(s)); } } return stack.pop(); } }