【题目来源】
https://www.luogu.com.cn/problem/P1981
【题目描述】
给定一个只包含加法和乘法的算术表达式,请你编程计算表达式的值。
【输入格式】
一行,为需要你计算的表达式,表达式中只包含数字、加法运算符 + 和乘法运算符 *,且没有括号,所有参与运算的数字均为 0 到 2^31-1 之间的整数。
输入数据保证这一行只有 0123456789+* 这 12 种字符。
【输出格式】
一个整数,表示这个表达式的值。
注意:当答案长度多于 4 位时,请只输出最后 4 位,前导 0 不输出。
【输入样例】
1+1234567890*1
【输出样例】
7891
【数据范围】
对于 30% 的数据,0≤表达式中加法运算符和乘法运算符的总数≤100。
对于 80% 的数据,0≤表达式中加法运算符和乘法运算符的总数≤1000。
对于 100% 的数据,0≤表达式中加法运算符和乘法运算符的总数≤100000。
【算法分析】
分别给出使用栈,及不用栈的两种代码。
【算法代码:栈】
cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MOD=10000;
int main() {
string s;
cin>>s;
s+='+';
stack<LL> stk;
LL num=0;
char op='+';
for(char ch:s) {
if(ch>='0' && ch<='9') {
num=(num*10+(ch-'0'))%MOD;
} else {
if(op=='+') stk.push(num);
else {
LL top=stk.top();
stk.pop();
stk.push(top*num%MOD);
}
op=ch;
num=0;
}
}
LL ans=0;
while(!stk.empty()) {
ans=(ans+stk.top())%MOD;
stk.pop();
}
cout<<ans<<endl;
return 0;
}
/*
in:
1+1234567890*1
out:
7891
*/
【算法代码二:不用栈】
cpp
#include <bits/stdc++.h>
using namespace std;
typedef long long LL;
const int MOD=10000;
int main() {
string s;
cin>>s;
s+='+';
LL ans=0, t=0, num=0;
char op='+';
for(char ch:s) {
if(ch>='0' && ch<='9') {
num=(num*10+(ch-'0'))%MOD;
} else {
if(op=='+') {
ans=(ans+t)%MOD;
t=num;
} else t=t*num%MOD;
op=ch;
num=0;
}
}
cout<<(ans+t)%MOD<<endl;
return 0;
}
/*
in:
1+1234567890*1
out:
7891
*/
【参考文献】
https://blog.csdn.net/hnjzsyjyj/article/details/149981270
https://blog.csdn.net/hnjzsyjyj/article/details/171820221
https://blog.csdn.net/hnjzsyjyj/article/details/148987127
https://blog.csdn.net/hnjzsyjyj/article/details/171820606