题解 | #四则运算#

四则运算

http://www.nowcoder.com/practice/9999764a61484d819056f807d2a91f1e

牛客HJ54的变形,多了两种括号

#include <algorithm>
#include <stack>

using namespace std;

bool priority(const char &a,const char &b){
    if(a=='('||a=='['||a=='{') return false;
    if(((a=='+')||(a=='-'))&&((b=='*')||(b=='/')))
        return false;
    
    return true;
    
}

void compute(stack<int> &si,stack<char> &sc){
    int a = si.top();
    si.pop();
    int b = si.top();
    si.pop();
    char op = sc.top();
    sc.pop();
    switch(op){
        case '+':a=b+a;break;
        case '-':a=b-a;break;
        case '*':a=b*a;break;
        case '/':a=b/a;break;
    }
    si.push(a);
    
}

int main() {
    string str;
    while(getline(cin,str)){
        stack<int> si;
        stack<char> sc;
        str = "("+str+")";
        int n =str.size();
        bool punct =false;
        for(int i =0;i<n;i++){
            if(str[i]=='('||str[i]=='['||str[i]=='{'){
                sc.push(str[i]);
            }
            /*else if(str[i]==')'){
                while(priority(sc.top(),str[i])){
                    compute(si,sc);
                }
                sc.pop();
            }*/
            else if(punct){
                while(priority(sc.top(),str[i])){
                    compute(si,sc);
                }
                
                sc.push(str[i]);
                punct = false;
                if(str[i]==')'||str[i]==']'||str[i]=='}'){
                    sc.pop();
                    sc.pop();
                    punct = true;
                }
            }
            else{
                int j = i;
                if(str[j]=='+'||str[j]=='-') j++;
                while(isdigit(str[j])){
                    j++;
                }
                string temp = str.substr(i,j-i);
                si.push(stoi(temp));
                i=j-1;
                punct = true;
            }
            
            
        }//for
        cout<<si.top()<<endl;
    }
}

全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务