此题采用栈的做法,先将字符串全部保存起来,然后逐个遍历,数字保留最后4位,不足4位的有多少位算多少位,用数字栈保存数字,用操作符栈保存操作符,有操作符入栈则先结算数字让数字入栈,然后进行操作符入栈操作,当操作符优先级低于运算符栈顶运算符时,将弹出所有高优先级的运算符并进行相应的运算,将演算结果压入数字栈中,最后计算时逐个弹出运算符栈中的运算符并进行计算,由于采用栈,注意考虑空栈情况,否则会段错误
#include <bits/stdc++.h>
using namespace std;
stack<char> tmp;
stack<int> num;
stack<char> oper;
void getnum()
{
string tmpstr;
int size = tmp.size();
for (int i = 1; i <= (size >= 4 ? 4 : size); i++)
{
tmpstr += tmp.top();
tmp.pop();
}
reverse(tmpstr.begin(), tmpstr.end());
stack<char>().swap(tmp);
num.push(stoi(tmpstr, 0, 10));
}
int main()
{
string str;
cin >> str;
for (auto ch : str)
{
if (ch == '*')
{
oper.push('*');
getnum();
}
else if (ch == '+')
{
getnum();
if (oper.size() != 0)
{
while (oper.top() == '*')
{
oper.pop();
int num1 = num.top();
num.pop();
int num2 = num.top();
num.pop();
num.push((num1 % 10000 * num2 % 10000) % 10000);
if(oper.size()==0)
break;
}
}
oper.push('+');
}
else
{
tmp.push(ch);
}
}
getnum();
while (!oper.empty())
{
char ch = oper.top();
oper.pop();
int num1 = num.top();
num.pop();
int num2 = num.top();
num.pop();
if (ch == '+')
num.push((num1 % 10000 + num2 % 10000) % 10000);
else
num.push((num1 % 10000 * num2 % 10000) % 10000);
}
cout << num.top();
}

京公网安备 11010502036488号