U2T5*1
作者:
疾风劲草
,
2021-06-24 06:26:51
,
所有人可见
,
阅读 335
- 读入数字,运算结果->进入数字栈;
- 如果当前元素是符号,则让他们先计算(当前大于栈顶则根据判断条件不计算)
- 最后记得op剩余的一起算
#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;
}