题解 | #四则运算#

四则运算

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

#include <iostream>
#include<map>
#include<stack>
using namespace std;

stack<int>nums;
stack<char>ops;
map<char,int>pri={{'+',1},{'-',1},{'*',2},{'/',2}};

void eval(){
    int b=nums.top();
    nums.pop();
    int a=nums.top();
    nums.pop();
    char op=ops.top();
    ops.pop(); 
    if(op=='+')nums.push(a+b);//cout<<a<<"+"<<b<<endl;
    else if(op=='-')nums.push(a-b);//cout<<a<<"-"<<b<<endl;
    else if(op=='*')nums.push(a*b);//cout<<a<<"*"<<b<<endl;
    else nums.push(a/b);//cout<<a<<"/"<<b<<endl;
}

bool isminus=true;

int main() {    
    string str;
    cin>>str;
    for(int i=0;i<str.size();i++){
        char ch=str[i];
        if(isdigit(ch)||(ch=='-'&&isminus)){
            int sign=1;
            if(!isdigit(ch))i++,sign=-1;
            int j=i,num=0;
            while(j<str.size()&&isdigit(str[j]))num=10*num+str[j]-'0',j++;
            nums.push(num*sign),i=j-1;
            // cout<<num*sign<<endl;
            isminus=false;
        }
        else if(ch=='('||ch=='['||ch=='{')ops.push(ch),isminus=true;
        else if(ch==')'||ch==']'||ch=='}'){
            while(ops.size()&&(ops.top()!='('&&ops.top()!='['&&ops.top()!='{'))eval();
            if(ops.size())ops.pop();
        }
        else {
            while(ops.size()&&(ops.top()!='('&&ops.top()!='['&&ops.top()!='{')&&pri[ops.top()]>=pri[ch])eval();
            ops.push(ch);
        }
    }
    while(ops.size())eval();
    cout<<nums.top();
    return 0;
}

全部评论

相关推荐

评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客企业服务