表达式求值
作者:
zzu
,
2024-04-08 21:36:59
,
所有人可见
,
阅读 2
#include <iostream>
#include <stack>
#include <unordered_map>
using namespace std;
stack<char> op;
stack<int> num;
void eval()
{
auto b = num.top(); num.pop();
auto a = num.top(); num.pop();
auto c = op.top(); op.pop();
int k = 0;
if(c == '+') k = a + b;
else if(c == '-') k = a - b;
else if(c == '*') k = a * b;
else k = a / b;
num.push(k);
}
int main()
{
string s;
cin >> s;
unordered_map<char, int> pr{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
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';
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() && op.top() != '(' && pr[s[i]] <= pr[op.top()])
eval();
op.push(s[i]);
}
}
while(op.size()) eval();
cout << num.top() << endl;
}