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
Use stack to hold the numbers and whenever meet a operator, we pop the top two number and calculate the result then push the result back to the stack. The final result would be remained in the stack.
public int evalRPN(String[] tokens) { int n = tokens.length; if(n == 0) return 0; Stack<Integer> nums = new Stack<Integer>(); for(int i = 0; i < n; i++) { if(tokens[i].equals("+")) { int num2 = nums.pop(); int num1 = nums.pop(); nums.push(num1 + num2); } else if(tokens[i].equals("-")) { int num2 = nums.pop(); int num1 = nums.pop(); nums.push(num1 - num2); } else if(tokens[i].equals("*")) { int num2 = nums.pop(); int num1 = nums.pop(); nums.push(num1 * num2); } else if(tokens[i].equals("/")) { int num2 = nums.pop(); int num1 = nums.pop(); nums.push(num1 / num2); } else { nums.push(Integer.parseInt(tokens[i])); } } return nums.pop(); }
没有评论:
发表评论