Evaluate the value of an arithmetic expression in .
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
逆波兰式,通常用stack解决。
public class Solution {
public int evalRPN(String[] tokens) { Stack<Integer> numbers = new Stack<Integer>(); for(String token : tokens) { switch(token) { case "+": case "-": case "*": case "/": int a = numbers.pop(); int b = numbers.pop(); numbers.push(eval(a,b,token)); break; default: numbers.push(Integer.parseInt(token)); } } return numbers.pop(); } private int eval(int a, int b, String operator) { switch(operator) { case "+": return b+a; case "-": return b-a; case "*": return b*a; case "/": return b/a; } return 0; }}