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
The concept is:
When meeting the number, push into the stack.
When meeting the operator, pop the top 2 number and compute the value, then push the result back into the stack.
Until the end of the expression.
Output the top (last) value in the stack.
1 public class Solution { 2 public int evalRPN(String[] tokens) { 3 if(tokens == null || tokens.length == 0) 4 return 0; 5 6 Stack<Integer> stack = new Stack<Integer>(); 7 8 for(int i = 0; i< tokens.length; i++){ 9 String s = tokens[i]; 10 // couldn't use switch(), because in java switch is not available for String 11 if(s.equals("+")){ 12 int num1 = stack.pop(); 13 int num2 = stack.pop(); 14 stack.push(num2 + num1); 15 }else if(s.equals("-")){ 16 int num1 = stack.pop(); 17 int num2 = stack.pop(); 18 stack.push(num2 - num1); 19 }else if(s.equals("*")){ 20 int num1 = stack.pop(); 21 int num2 = stack.pop(); 22 stack.push(num2 * num1); 23 }else if(s.equals("/")){ 24 int num1 = stack.pop(); 25 int num2 = stack.pop(); 26 stack.push(num2 / num1); 27 }else{ 28 stack.push(Integer.valueOf(s)); 29 } 30 } 31 32 return stack.pop(); 33 } 34 }