题解 | #四则运算#

四则运算

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

#include <bits/stdc++.h>
using namespace std;
//创建两个栈,一个操作数栈一个符号栈
const int maxn=1e3+5;
int num[maxn];
char operation[maxn];
int cnt1,cnt2;//两个指针
//判断当前输入的算符和栈顶算符优先级函数//栈顶优先级低,入栈,否则计算
int YouXian(char c){
    char top=operation[cnt2];
    if(top=='*'||top=='/'){
        if(c=='+'||c=='-'||c=='*'||c=='/'||c==')'||c==']'||c=='}'||c=='#')
            return 1;//计算
        return -1;//(,[,{
    }
    else if(top=='+'||top=='-'){
        if(c=='+'||c=='-'||c==')'||c==']'||c=='}'||c=='#')
            return 1;
        return -1;
    }
    else if(top=='{'){
        if(c=='}')
            return 0;
        return -1;
    }
    else if(top=='['){
        if(c==']')
            return 0;
        return -1;
    }
    else if(top=='('){
        if(c==')')
            return 0;
        return -1;
    }
    else if(top=='}'||top==']'||top==')')
        return 1;
    else{//#
        if(c=='#')
            return 0;
        return -1;
    }
}
int main(){
    string s;
    int ans=0;
    while(cin>>s){
        s=s+"#";//添加判断符号
        operation[++cnt2]='#';
        char cur='?';
        for(int i=0;i<s.length();i++){
            if(operation[cnt2]=='#'&&s[i]=='#')
                break;
            int j=i;
            if((s[i]=='('||s[i]=='['||s[i]=='{') && i<s.length() - 1 && s[i + 1] == '-')
                num[++cnt1]=0;
            while(isdigit(s[i]))    i++;
            if(j!=i)    num[++cnt1]=stoi(s.substr(j,i-j));
            cur=s[i];
            int ans2=YouXian(cur);
            if(ans2==-1){
                operation[++cnt2]=cur;continue;
            }
            else if(ans2==0){
                cnt2--;continue;
            }
            else{
                int b=num[cnt1],a=num[--cnt1];
                char top=operation[cnt2];
                cnt2--;i--;
                num[cnt1]=top=='*'?a*b:top=='/'?a/b:top=='+'?a+b:a-b;
            }
        }
    cout<<num[1]<<endl;
    }
    
}
全部评论

相关推荐

02-05 08:49
已编辑
武汉大学 Web前端
野猪不是猪🐗:36k和36k之间亦有差距,ms的36k和pdd的36k不是一个概念
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务