150. Evaluate Reverse Polish Notation

注意包装类的转换。

public int evalRPN(String[] tokens) {
    LinkedList<Integer> stack = new LinkedList<>();
    for (String token : tokens) {
        if (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")) {
            int a = stack.pop();
            int b = stack.pop();
            if (token.equals("+")) {
                stack.push(b + a);
            } else if (token.equals("-")) {
                stack.push(b - a);
            } else if(token.equals("*")) {
                stack.push(b * a);
            } else {
                stack.push(b / a);
            }
        } else {
                stack.push(Integer.valueOf(token));
        }
    }
    return stack.pop();
}

强行换成switch case

public int evalRPN(String[] tokens) {
    LinkedList<Integer> stack = new LinkedList<>();
    for (String token : tokens) {
        if (token.equals("+") || token.equals("-") || token.equals("*") || token.equals("/")) {
            int a = stack.pop();
            int b = stack.pop();
            switch (token) {
                case "+": stack.push(b + a); break;
                case "-": stack.push (b - a); break;
                case "*": stack.push(b * a); break;
                case "/": stack.push(b / a); break;
            }
        } else {
                stack.push(Integer.valueOf(token));
        }
    }
    return stack.pop();
}

results matching ""

    No results matching ""