首页 > 其他 > 详细

150. Evaluate Reverse Polish Notation

时间:2016-06-02 11:03:55      阅读:198      评论:0      收藏:0      [点我收藏+]
    /*
     *150. Evaluate Reverse Polish Notation
     * 1.1 by Mingyang
     * 这里我开始想的是把string变成char再来判断是数字还是符号,但是我发现错了!因为这里string变成char非常难!!!
     * 所以Integer.parseInt(tokens[i]就可以很好的解决这个问题,直接变为int,包括你的符号!!!!
     */    
    public int evalRPN(String[] tokens) {
        Stack<Integer> stack = new Stack<Integer>();
        int a, b;
        for (int i = 0; i < tokens.length; i++) {
            if (tokens[i].equals("+")) {
                a = stack.pop();
                b = stack.pop();
                stack.push(b + a);
            } else if (tokens[i].equals("-")) {
                a = stack.pop();
                b = stack.pop();
                stack.push(b - a);
            } else if (tokens[i].equals("*")) {
                a = stack.pop();
                b = stack.pop();
                stack.push(b * a);
            } else if (tokens[i].equals("/")) {
                a = stack.pop();
                b = stack.pop();
                stack.push(b / a);
            } else {
                stack.push(Integer.parseInt(tokens[i]));
            }
        }
        return stack.pop();
    }

 

150. Evaluate Reverse Polish Notation

原文:http://www.cnblogs.com/zmyvszk/p/5551954.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!