標籤:des style blog color strong for
Problem Description:
Evaluate the value of an arithmetic expression in Reverse Polish Notation.
Valid operators are +, -, *, /. Each operand may be an integer or another expression.
Solution:
1 public int evalRPN(String[] tokens) { 2 Stack<String> operands = new Stack<String>(); 3 for (int i = 0; i < tokens.length; i++) { 4 if (!(tokens[i].equals("+") || tokens[i].equals("-") || tokens[i].equals("*") || tokens[i].equals("/"))) { 5 operands.push(tokens[i]); 6 } else { 7 String opRight = operands.pop(); 8 String opLeft = operands.pop(); 9 String result = "";10 if (tokens[i].equals("+")) {11 result = String.valueOf(Integer.valueOf(opLeft) + Integer.valueOf(opRight));12 } else if (tokens[i].equals("-")) {13 result = String.valueOf(Integer.valueOf(opLeft) - Integer.valueOf(opRight));14 } else if (tokens[i].equals("*")) {15 result = String.valueOf(Integer.valueOf(opLeft) * Integer.valueOf(opRight));16 } else if (tokens[i].equals("/")) {17 result = String.valueOf(Integer.valueOf(opLeft) / Integer.valueOf(opRight));18 } 19 operands.push(result);20 }21 }22 23 return Integer.valueOf(operands.pop());24 }