练习链接:表达式求值
#include<iostream>
#include<unordered_map>
#include<string>
#include<cstring>
#include<algorithm>
#include<stack>
using namespace std;
stack<int>num;
stack<char>op;
void eval()
{
int b=num.top();num.pop();
int a=num.top();num.pop();
char c=op.top();op.pop();
if(c=='+')
{
num.push(a+b);
}
else if(c=='-')
{
num.push(a-b);
}
else if(c=='*')
{
num.push(a*b);
}
else
{
num.push(a/b);
}
}
int main(void)
{
unordered_map<char,int>pr={{'+',1},{'-',1},{'*',2},{'/',2}};
string str;
cin>>str;
for(int i=0;i<str.size();i++)
{
auto c=str[i];
if(isdigit(c))
{
int x=0,j=i;
while(j<str.size()&&isdigit(str[j]))
{
x=x*10+str[j++]-'0';
}
i=j-1;
num.push(x);
}
else if(c=='(')
{
op.push(str[i]);
}
else if(c==')')
{
while(op.top()!='(')
{
eval();
}
op.pop();
}
else
{
while(op.size()&&pr[op.top()]>=pr[c])
{
eval();
}
op.push(c);
}
}
while(op.size())
{
eval();
}
printf("%d",num.top());
return 0;
}