#include<cstdio>
#include<iostream>
#include<cstring>
#include<stack>
#include<string>
using namespace std;
string xy;
stack <char> ss;
stack <long long> n;
long long ans;
int len;
int main()
{
int i = 0;
getline(cin, xy);
len = xy.length();
while (i <= len - 1)
{
int t = 0;
bool f = false;
while (xy[i] >= '0'&&xy[i] <= '9') //进数字的操作
{
t = t * 10 + (xy[i] - 48);
f = true;
i++;
}
if (f)
{
n.push(t % 10000);
if (ss.size() >= 1 && ss.top() == '*')
{
int k = n.top();
ss.pop();
n.pop();
k *= n.top();
n.pop();
n.push(k % 10000);
}
}
if (xy[i] == '+' || xy[i] == '*')
{
ss.push(xy[i]);
i++;
}
}
int size = n.size();
for (i = 1; i <= size; i++) //计算和
{
ans += n.top();
n.pop();
ans %= 10000;
}
cout<< ans % 10000;
return 0;
}
#include<bits/stdc++.h>
using namespace std;
stack<int>q;
stack<char>p;
string s;
int temp1=0, temp2=0;
int main()
{
cin >> s;
int i;
int sum = 0;
for (i = 0; i < s.length(); i++)
{
if (s[i] >= '0'&&s[i] <= '9')//是数字
{
if (s[i + 1] >= '0'&&s[i + 1] <= '9')//下一位也是数字
{
sum = sum * 10 + s[i + 1] - '0';
}
else//数字的下一位是符号
{
sum = (sum * 10 + s[i] - '0') % 10000;//放入之前都取一下模
q.push(sum);
sum = 0;
}
}
if (s[i] < '0')//是符号
{
//*号在+号后面
if (p.empty())//如果为空就要初始化
{
p.push(s[i]);
}
if (s[i] < p.top())//符号优先级高
p.push(s[i]);
else//符号同级或低级的话就先运算优先级高的运算符
{
temp1 = p.top();
p.pop();
temp2 = p.top();
p.pop();
if (q.top() == '*')
{
int t = (temp1*temp2) % 10000;
p.push(t);
q.pop();
q.push(s[i]);
}
if (q.top() == '+')
{
int t = (temp1 + temp2) % 10000;
p.push(t);
q.pop();
q.push(s[i]);
}
}
}
}//初始化完毕
while (!q.empty())
{
temp1 = p.top();
p.pop();
temp2 = p.top();
p.pop();
char y = q.top();
if (y == '*')
{
int t = (temp1 * temp2) % 10000;
p.push(t);
q.pop();
}
if (y == '+')
{
int t = (temp1 + temp2) % 10000;
p.push(t);
q.pop();
}
}
int ans = p.top();
cout << ans << endl;
}
记录一下自己的错误:
这个是超时了我想是因为相较于第一个赋值操作变多了导致代码不够简洁
这道题的思路大概就是第一个代码块一样,时间复杂度是n在n次循环中设置三个if,第一个就是用来读取数字,第二个if用来计算比加法优先度更高的乘法运算,每次将读入栈中数字之后,就判断以下字符栈的栈顶是不是乘法,这样一来就使得字符栈中最后只存有+号。第三个if当读入运算符时,将其放入字符栈中。