码迷,mamicode.com
首页 > 其他好文 > 详细

224. Basic Calculator

时间:2016-06-13 13:25:58      阅读:126      评论: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
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!