AcWing 3302. 表达式求值
原题链接
简单
作者:
疾风劲草
,
2021-06-24 06:23:30
,
所有人可见
,
阅读 132
#include<iostream>
#include<stack>
#include<unordered_map>
using namespace std;
stack<int>num;
stack<char>op;
unordered_map<char,int>prefer{{'(',0},{'+',1},{'-',1},{'*',2},{'/',2}};
void eval()
{
int b=num.top();num.pop();
int a=num.top();num.pop();
char c=op.top();op.pop();
int r;
if(c=='+')
r=a+b;
if(c=='-')
r=a-b;
if(c=='*')
r=a*b;
if(c=='/')
r=a/b;
num.push(r);
}
int main()
{
string str;
cin>>str;
for(int i=0;str[i];i++)
{
if(isdigit(str[i]))
{
int x=0,j=i;
while(str[j]&&isdigit(str[j]))
{
x=x*10+str[j]-'0';
j++;
}
i=j-1;
num.push(x);
}
else if(str[i]=='(')
op.push(str[i]);
else if(str[i]==')')
{
while(op.top()!='(')
eval();
op.pop();
}
else
{
while(!op.empty()&&prefer[op.top()]>=prefer[str[i]])
eval();
op.push(str[i]);
}
}
while(!op.empty())
eval();
cout<<num.top()<<endl;
}