AcWing
  • 首页
  • 课程
  • 题库
  • 更多
    • 竞赛
    • 题解
    • 分享
    • 问答
    • 应用
    • 校园
  • 关闭
    历史记录
    清除记录
    猜你想搜
    AcWing热点
  • App
  • 登录/注册

AcWing 3302. 表达式求值    原题链接    中等

作者: 作者的头像   痛苦大一学弟 ,  2025-05-10 14:01:11 · 重庆 ,  所有人可见 ,  阅读 1


0


#include<iostream>
#include<stack>
#include<unordered_map>
#include<string>
using namespace std;
stack<int> num;
stack<char> op;
unordered_map<char,int> h{ {'+',1},{'-',1},{'*',2},{'/',2}};
void eval()
{
    int x;
    int b=num.top();//第二个操作数 
    num.pop();
    int a=num.top();//第一个操作数
    num.pop();
    char c=op.top();
    op.pop(); 
    if(c=='+')x=a+b;
    if(c=='-')x=a-b;
    if(c=='*')x=a*b;
    if(c=='/')x=a/b;
    num.push(x);
}
int main()
{
    string s;
    cin>>s;
    for(int i=0;i<s.size();i++)
    {
        if(isdigit(s[i]))
        {
            int x=0,j=i;
            while(j<s.size()&&isdigit(s[j]))
            {
                x=x*10+s[j]-'0';
                j++;
            }
            num.push(x);
            i=j-1;
        }
        else if(s[i]=='(')
        {
            op.push(s[i]);
        }
        else if(s[i]==')')
        {
            while(op.top()!='(')
            eval();
            op.pop();//左括号删除 
        }
        else 
        {
            while(op.size()&&h[op.top()]>=h[s[i]])
            eval();
            op.push(s[i]);
        }
     } 
     while(op.size())eval();
     cout<<num.top();
     return 0;
}

0 评论

App 内打开
你确定删除吗?
1024
x

© 2018-2025 AcWing 版权所有  |  京ICP备2021015969号-2
用户协议  |  隐私政策  |  常见问题  |  联系我们
AcWing
请输入登录信息
更多登录方式: 微信图标 qq图标 qq图标
请输入绑定的邮箱地址
请输入注册信息