150. Evaluate Reverse Polish Notation

class Solution {
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack=new Stack<Integer>();
        for(String token:tokens)
        {
            if(token.equals("+")||token.equals("-")||token.equals("*")||token.equals("/"))
            {
                int n2=stack.pop();
                int n1=stack.pop();
                if(token.equals("+"))
                    stack.push(n1+n2);
                else if(token.equals("-"))
                    stack.push(n1-n2);
                else if(token.equals("*"))
                    stack.push(n1*n2);
                else
                    stack.push(n1/n2);
            }
            else
                stack.push(Integer.parseInt(token));
        }
        return stack.isEmpty()?0:stack.pop();
    }
}

  

posted @ 2017-10-17 10:40  Weiyu Wang  阅读(106)  评论(0编辑  收藏  举报