AcWing 3302. 表达式求值
原题链接
简单
作者:
dsyami
,
2021-05-11 16:38:45
,
所有人可见
,
阅读 158
#include <iostream>
#include <algorithm>
#include <stack>
#include <unordered_map>
using namespace std;
unordered_map<char, int> pr {{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
stack<int> num;
stack<char> op;
void eval()
{
int a, b, x;
char c;
b = num.top(); num.pop();
a = num.top(); num.pop();
c = op.top(); op.pop();
if(c == '+') x = a + b;
else if(c == '-') x = a- b;
else if(c == '*') x = a * b;
else x = a / b;
num.push(x);
}
int main()
{
string str;
cin >> str;
for(int i = 0; i < str.size(); i ++ )
{
if(isdigit(str[i]))
{
int x = 0, j = i;
while(j < str.size() && isdigit(str[j]))
x = x * 10 + str[j ++ ] - '0';
num.push(x);
i = j - 1;
}
else if(str[i] == '(') op.push(str[i]);
else if(str[i] == ')')
{
while(op.top() != '(') eval();
op.pop();
}
else
{
while(op.size() && pr[op.top()] >= pr[str[i]]) eval();
op.push(str[i]);
}
}
while(op.size()) eval();
cout << num.top() << endl;
return 0;
}