首页 > 其他 > 详细

224. Basic Calculator

时间:2016-06-13 13:23:05      阅读:183      评论:0      收藏:0      [点我收藏+]
    /*
     * 224. Basic Calculator
     * 12.10 by Mingyang
     * 遇到 ‘(‘ 就把之前的结果和符号push进stack. 遇到‘)‘就把 当前结果*stack中的符号 再加上stack中之前的结果.
     */
     public int calculate(String s) {
            Stack<Integer> stack = new Stack<Integer>();
            int result = 0;
            int number = 0;
            int sign = 1;
            for(int i = 0; i < s.length(); i++){
                char c = s.charAt(i);
                if(Character.isDigit(c)){
                    number = 10 * number + (int)(c - ‘0‘);
                }else if(c == ‘+‘){
                    result += sign * number;
                    number = 0;
                    sign = 1;
                }else if(c == ‘-‘){
                    result += sign * number;
                    number = 0;
                    sign = -1;
                }else if(c == ‘(‘){
                    //we push the result first, then sign;
                    stack.push(result);
                    stack.push(sign);
                    //reset the sign and result for the value in the parenthesis
                    sign = 1;   
                    result = 0;
                }else if(c == ‘)‘){
                    result += sign * number;  
                    number = 0;
                    result *= stack.pop();    //stack.pop() is the sign before the parenthesis
                    result += stack.pop();   //stack.pop() now is the result calculated before the parenthesis

                }
            }
            if(number != 0) result += sign * number;
            return result;
        }

 

224. Basic Calculator

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

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