Acwing_算法基础_数据结构_3302_表达式求值

AcWing 3302. 表达式求值

#include<iostream>
#include<stack>
#include<string>
#include<unordered_map>
using namespace std;
//定义优先级,与平常运算的优先级一样
/*
 * 考虑一个表达式 1+2+3*4*5
 * 两个栈 一个数字栈 一个符号栈
 * 如果符号栈顶的运算符优先级低,新运算符直接入栈
 * 如果符号栈顶的运算符优先级高,先出栈计算,新运算符再入栈
 * 相同符号先出栈计算,不同符号看优先级
 */
unordered_map<char,int> h={{'+',1},{'-',1},{'*',2},{'/',2}};
stack<int> nums;
stack<char> op;
//计算函数,得到的最终值要加入到数字栈中
void eval(){
    int a=nums.top();
    nums.pop();
    int b=nums.top();
    nums.pop();
    int p=op.top();
    op.pop();
    int r=0;
    if(p=='+') r=b+a;
    if(p=='-') r=b-a;
    if(p=='*') r=b*a;
    //唯一要想清楚的是谁除以谁
    if(p=='/') r=b/a;
    nums.push(r);
}
int main(){
    string s;
    cin>>s;
    for(int i=0;i<s[i];i++){
        if(isdigit(s[i])){
            //这是string类型转数值的方法
            int x=0,j=i;
            while(j<s.size()&& isdigit(s[j])){
                x=x*10+(s[j]-'0');
                j++;
            }
            nums.push(x);
            i=j-1;
        }
        //遇到括号的策略:左括号直接加入,遇到右括号运算到栈顶为左括号为止
        else if(s[i]=='('){
            op.push(s[i]);
        }
        else if(s[i]==')'){
            while(op.top()!='(') eval();
            op.pop();
        }
        //通过判断优先级来计算
        else{
            if(op.size()&&h[op.top()]>=h[s[i]]) eval();
            op.push(s[i]);
        }
    }
    while(op.size()) eval();
    cout<<nums.top()<<endl;
    return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值