前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >每日一题春季系列 (六) AcWing 3302. 表达式求值 ( 四则运算带括号 三分钟模板建议背下来)

每日一题春季系列 (六) AcWing 3302. 表达式求值 ( 四则运算带括号 三分钟模板建议背下来)

作者头像
glm233
发布2021-03-23 12:02:08
3450
发布2021-03-23 12:02:08
举报
文章被收录于专栏:glm的全栈学习之路

啥也不说了 这题已经明示python eval语法糖不能用了 老实点上双栈写个表达式求值吧~

代码语言:javascript
复制
#include<bits/stdc++.h>
using namespace std;
unordered_map<char,int>p{{'+',1},{'-',1},{'*',2},{'/',2}};
stack<int>num;
stack<char>op;
void eval(){
    auto b=num.top();num.pop();
    auto a=num.top();num.pop();
    auto c=op.top();op.pop();
    int x;
    if(c=='-'){
        x=a-b;
    }
    else if(c=='+')x=a+b;
    else if(c=='*')x=a*b;
    else x=a/b;
    num.push(x);
}
string s;
int main(){
    cin>>s;
    for(int i=0;s[i];i++){
        char c=s[i];
        if(isdigit(c)){
            int j=i,sum=0;
            while(j<s.size()&&isdigit(s[j])){
                sum=sum*10+s[j++]-'0';
            }
            i=j-1;
            num.push(sum);
        }
        else if(c=='('){
            op.push(c);
        }
        else if(c==')'){
            while(op.top()!='(')eval();
            op.pop();
        }
        else{
            while(!op.empty()&&p[op.top()]>=p[c])eval();
            op.push(c);
        }
        
    }while(!op.empty())eval();
    cout<<num.top()<<endl;
}
本文参与 腾讯云自媒体同步曝光计划,分享自作者个人站点/博客。
原始发表:2021/03/21 ,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 作者个人站点/博客 前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体同步曝光计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档