leetcode 224. Basic Calculator

https://www.cnblogs.com/grandyang/p/4570699.html

 

class Solution {
public:
    int calculate(string s) {
        int sign=1,res=0,n=s.size();
        stack<int> sta;
        for(int i=0;i<n;++i) {
            char c=s[i];
            if(c>='0') {
                int num=0;
                while(i<n&&s[i]>='0') num=num*10+(s[i++]-'0');
                res+=sign*num;
                --i;
            }
            else if(c=='+') sign=1;
            else if(c=='-') sign=-1;
            else if(c=='(') {
                sta.push(res);
                sta.push(sign);
                res=0;sign=1;
            }
            else if(c==')') {
                res*=sta.top();sta.pop();
                res+=sta.top();sta.pop();
            }
        }
        return res;
    }
};

 

posted @ 2020-06-27 17:54  qiujiejie  阅读(82)  评论(0编辑  收藏  举报