AcWing 3302. 表达式求值
原题链接
中等
作者:
痛苦大一学弟
,
2025-05-10 14:01:11
· 重庆
,
所有人可见
,
阅读 1
#include<iostream>
#include<stack>
#include<unordered_map>
#include<string>
using namespace std;
stack<int> num;
stack<char> op;
unordered_map<char,int> h{ {'+',1},{'-',1},{'*',2},{'/',2}};
void eval()
{
int x;
int b=num.top();//第二个操作数
num.pop();
int a=num.top();//第一个操作数
num.pop();
char c=op.top();
op.pop();
if(c=='+')x=a+b;
if(c=='-')x=a-b;
if(c=='*')x=a*b;
if(c=='/')x=a/b;
num.push(x);
}
int main()
{
string s;
cin>>s;
for(int i=0;i<s.size();i++)
{
if(isdigit(s[i]))
{
int x=0,j=i;
while(j<s.size()&&isdigit(s[j]))
{
x=x*10+s[j]-'0';
j++;
}
num.push(x);
i=j-1;
}
else if(s[i]=='(')
{
op.push(s[i]);
}
else if(s[i]==')')
{
while(op.top()!='(')
eval();
op.pop();//左括号删除
}
else
{
while(op.size()&&h[op.top()]>=h[s[i]])
eval();
op.push(s[i]);
}
}
while(op.size())eval();
cout<<num.top();
return 0;
}