class Solution {
public:
    stack<int> OPD;
    stack<char> OPR;
    int calculate(int num1, int num2, char opr){
        switch (opr){
        case '+':{
                     return num1 + num2;
        }
        case '-':{
                     return num1 - num2;
        }
        case '*':{
                     return num1*num2;
        }
        case '/':{
                     return num1 / num2;
        }
        }
    }
    int calculate(string s) {
        int len = s.size();
        int i=0;
        while(i<len){
            if (s[i] == ' '){
                i++;
            }
            else if (s[i] == '+' || s[i] == '-' || s[i]=='*' || s[i]=='/'){
                OPR.push(s[i]);
                i++;
            }
            else{
                int num = 0;
                while (i < len && s[i] >= '0' && s[i] <= '9'){
                    num = num * 10 + (s[i] - '0');
                    i++;
                }
                if (!OPR.empty() && (OPR.top()=='/' || OPR.top()=='*')){
                    num = calculate(OPD.top(),num,OPR.top());
                    OPR.pop();
                    OPD.pop();
                }
                OPD.push(num);
            }
        }
        int res=0;
        while (!OPR.empty()){
            int tmp=OPD.top();
            char ch=OPR.top();
            if(ch=='-'){
                tmp=-tmp;
            }
            res+=tmp;
            OPD.pop();
            OPR.pop();
        }
        res+=OPD.top();
        return res;
    }
};

 

posted on 2018-10-19 11:04  Sempron2800+  阅读(111)  评论(0编辑  收藏  举报