Evaluate Reverse Polish Notation

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

public class Solution {
    public int evalRPN(String[] tokens) {
           Stack stack = new Stack();
        for(int i=0;i<tokens.length;i++){
            if (tokens[i].equals("+")){
                int op1 = Integer.parseInt(String.valueOf(stack.pop()));
                int op2 = Integer.parseInt(String.valueOf(stack.pop()));
                stack.push(op2+op1);
            }else if (tokens[i].equals("-")){
                int op1 = Integer.parseInt(String.valueOf(stack.pop()));
                int op2 = Integer.parseInt(String.valueOf(stack.pop()));
                stack.push(op2-op1);
            }else if (tokens[i].equals("*")){
                int op1 = Integer.parseInt(String.valueOf(stack.pop()));
                int op2 = Integer.parseInt(String.valueOf(stack.pop()));
                stack.push(op2*op1);
            }else if (tokens[i].equals("/")){
                int op1 = Integer.parseInt(String.valueOf(stack.pop()));
                int op2 = Integer.parseInt(String.valueOf(stack.pop()));
                if (op1==0) {
                    return -1;
                }
                stack.push(op2/op1);
            } else {
                stack.push(tokens[i]);
            }
        }
        return Integer.parseInt(String.valueOf(stack.pop()));
    }
}

 

posted @ 2014-01-06 11:14  23lalala  阅读(130)  评论(0编辑  收藏  举报