#include<bits/stdc++.h>
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()
{
string ch;
cin>>ch;
unordered_map<char, int> priority{{'+', 1}, {'-', 1}, {'/', 2}, {'*', 2}};
int len = ch.length();
for(int i=0;i<len;++i)
{
if(ch[i] >= '0' && ch[i] <= '9')
{
int sum = 0, j = i;
while(j < len && ch[j] >= '0' && ch[j] <= '9')
sum = sum*10 + ch[j++] - '0';
i = j - 1;
num.push(sum);
}
else if(ch[i] == '(') op.push('(');
else if(ch[i] == ')')
{
while(op.top() != '(') eval();
op.pop();
}
else
{
while(!op.empty() && priority[ch[i]] <= priority[op.top()]) eval();
op.push(ch[i]);
}
}
while(!op.empty()) eval();
cout<<num.top();
return 0;
}
【Acwing】表达式求值(栈)
于 2024-02-27 21:29:31 首次发布