分析
中缀表达式,对计算的优先级进行划分,之后依次计算。
#include <bits/stdc++.h>
const int N = 1e5+10;
using namespace std;
map<char,int> pri;
int n,x,ans;
string s;
stack<int> num;
stack<char> op;
void eval()
{
auto a=num.top(); num.pop();
auto b=num.top(); num.pop();
auto c=op.top(); op.pop();
if(c=='+') b=(a+b)%10000;
if(c=='*') b=(b*a)%10000;
num.push(b);
// cout<<b<<endl;
}
int main()
{
pri['+']=1,pri['*']=2;
cin>>s;
for(int i=0;i<s.size();i++)
{
if(s[i]>='0' && s[i]<='9')
{
int j=i,temp=0;
while(j<s.size() && s[j]>='0' && s[j]<='9')
{
temp=temp*10+(s[j]-'0');
j++;
}
i=j-1;
num.push(temp);
}
else{
while(op.size() && pri[s[i]]<=pri[op.top()]) eval();
op.push(s[i]);
}
}
while(op.size())
{
eval();
}
cout<<num.top()%10000;
return 0;
}
本文解析了如何使用C++实现中缀表达式的求值,通过分析运算符优先级,逐层计算并应用到栈结构中,详细展示了代码片段。
1456

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



