表达式求值(stack实现)

题目链接:表达式求值

模板:

#include<iostream>
#include<cstdio>
#include<algorithm>
#include<cstring>
#include<stack>
using namespace std;

char line[5000005];
long long ans,x,y;
stack <int> s;
const int MOD = 10000;
int main(){
    scanf("%s",line);
    int n = strlen(line);
    for(int i = 0;i < n;++ i)
    {
        if(line[i] < '0' || line[i] > '9')
            s.push(x),x = 0;
        else
            x = x*10+line[i]-'0';//别忘了两位以上的数
    }
    s.push(x),x = 0;//最后一个数字在循环中会被漏掉,所以要补上
    for(int i = n-1;i >= 0;i--)
    {
        if(line[i] >= '0' && line[i] <= '9')
            continue;
        if(line[i] == '+')
        {
            ans = (ans + s.top()) % MOD;
            s.pop();
        }
        else if(line[i] == '*')
        {
            x = s.top() % MOD;
            s.pop();
            y = s.top() % MOD;
            s.pop();
            x = (x * y) % MOD;
            //随时取模防止溢出
            s.push(x);
        }
    }
    ans = (ans + s.top()) % MOD;
    s.pop();//同样最后一个数字会漏掉,而且一定是相加关系,因为乘号得出的权值已经处理完
    printf("%lld\n",ans);
    return 0;
}

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值