题解 | #四则运算#

四则运算

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;
    }
}

全部评论

相关推荐

程序员小白条:你是沟通了900个,不是投了900份简历,你能投900份,意味着对面都要回复你900次,你早就找到实习了,没亮点就是这样的,别局限地区,时间投的也要早,现在都要7月了
点赞 评论 收藏
分享
那一天的Java_J...:他本来公司就是做这个的,不就是正常的游戏客户端和服务器开发,软硬件联动,有啥恶心不恶心的,提前告诉你就是怕你接受不了,接受不了就没必要再往后走流程浪费时间,虽然这公司是一坨。
点赞 评论 收藏
分享
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务