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

224. Basic Calculator

时间:2016-12-01 07:44:10      阅读:118      评论:0      收藏:0      [点我收藏+]

标签:new   pac   for   empty   ace   tor   har   cti   examples   

Implement a basic calculator to evaluate a simple expression string.

The expression string may contain open ( and closing parentheses ), the plus + or minus sign -, non-negative integers and empty spaces .

You may assume that the given expression is always valid.

Some examples:

"1 + 1" = 2
" 2-1 + 2 " = 3
"(1+(4+5+2)-3)+(6+8)" = 23

 

Note: Do not use the eval built-in library function.

 

分析:

 one pass 

1. curNum  存目前的值

2. 遇到 + - , res += curNum * sign , sign 存+-

3.有()用一个stack存目前的res 和sign;

// res curNum 0 - 9 ; 10 -...
public class Solution {
    public int calculate(String s) {
        if(s == null || s.length() == 0){
            return 0;
        }
        Stack<Integer> stack = new Stack<>();
        int res = 0;
        int curNum = 0;
        int sign = 1;
        for(int i = 0 ; i < s.length(); i++){
            char temp = s.charAt(i);
            if(temp == ‘ ‘) 
                continue;
            else if(Character.isDigit(temp)) 
                curNum = curNum * 10 + (int) (temp - ‘0‘);
            else if( temp ==  ‘+‘){
                res += sign * curNum;
                curNum = 0;
                sign = 1;
            }
            else if(temp == ‘-‘){
                res += sign * curNum;
                curNum = 0;
                sign = -1;  //prepare for ();
            }
            else if(temp == ‘(‘){
                stack.push(res);
                stack.push(sign);
                res = 0;
                curNum = 0;
                sign = 1;
            }
            else if(temp == ‘)‘){
                res += curNum * sign;
                if(!stack.isEmpty())
                    sign = stack.pop();
                if(!stack.isEmpty())
                    res = res * sign + stack.pop();
                curNum = 0;
                sign = 1;
            }
        }
        if(curNum != 0)
            res += curNum * sign;
            
        return res;
    }
}

 

224. Basic Calculator

标签:new   pac   for   empty   ace   tor   har   cti   examples   

原文地址:http://www.cnblogs.com/joannacode/p/6120496.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!