表达式求值 (栈)

表达式求值算法

题目:https://ac.nowcoder.com/acm/contest/3186/B

输入仅有一行,为需要你计算的表达式,
表达式中只包含数字、加法运算符“+”和乘法运算符“*”,且没有括号。 所有参与运算的数字均为 0 到231-1 之间的整数。 输入数据保证这一行只有0~9、+、*这12种字符。

输出只有一行,包含一个整数,表示这个表达式的值。注意:当答案长度多于4位时,请只输出最后4位,前导0不输出。

样例输入:1+1*3+4
样例输出:8

样例输入:1+1000000003*1
样例输出:4

code:

#include<iostream>
#include<algorithm>
#include<cstring>
#include<string>
#include<cstdio>
using namespace std;
const int INF = 0x3f3f3f3f;
const int MAXN = 1e7 + 7;
int num[MAXN], topnum = 0; //存操作数
char op[MAXN]; int topop = 0; //存操作符
int judge(char c) //判断操作符优先级
{
    if(c == '+') return 1;
    else return 2;
}
void calculat() //计算
{
    if(topnum < 2) return ;
    int num1 = num[--topnum]; num[topnum] = 0;
    int num2 = num[--topnum]; num[topnum] = 0;
    char c = op[--topop];  op[topop] = 0;

    if(c == '+')
    {
        num1 += num2;
    }
    else if(c == '*')
    {
        num1 *= num2;
    }
    num[topnum++] = num1 % 10000 ;
}
void pushOp(char c)
{
    while(topop > 0 && (judge(c) < judge(op[topop - 1]))) //如果上一个操作的优先级比较大,就把前面的数进行计算
    {
        calculat();
    }
    op[topop++] = c;
}
int main()
{
    char c;
    while(~scanf("%c", &c))
    {
        if(c >= '0' && c <= '9')
            num[topnum] = ((num[topnum] * 10) % 10000 + (c - '0')) % 10000;
        else
        {
            topnum++;
            pushOp(c);
        }
    }

    topop--;

    while(topop > 0)
    {
        calculat();
    }
    printf("%d\n", num[0]);
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值