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
Solution:
public class Solution { public int evalRPN(String[] tokens) { Stack<String> stack = new Stack<String>(); int len = tokens.length; for(int i = 0;i < len;i++){ if(tokens[i].equals("+") || tokens[i].equals("/") || tokens[i].equals("*") || tokens[i].equals("-")){ String b = stack.pop(); // String a = stack.pop(); // 这里要注意返回的顺序 int result = 0; if(tokens[i].equals("+")){ result = Integer.parseInt(a) + Integer.parseInt(b); } if(tokens[i].equals("/")){ result = Integer.parseInt(a) / Integer.parseInt(b); } if(tokens[i].equals("*")){ result = Integer.parseInt(a) * Integer.parseInt(b); } if(tokens[i].equals("-")){ result = Integer.parseInt(a) - Integer.parseInt(b); } String StringFormatResult = result + ""; stack.push(StringFormatResult); }else{ stack.push(tokens[i]); } } return Integer.parseInt(stack.pop()); } }