题目: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;
}
表达式求值算法

被折叠的 条评论
为什么被折叠?



