You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
66 lines
1.2 KiB
66 lines
1.2 KiB
#include <bits/stdc++.h>
|
|
|
|
using namespace std;
|
|
|
|
stack<int> num;
|
|
stack<char> stk;
|
|
|
|
unordered_map<char, int> h{{'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
|
|
|
|
void eval() {
|
|
int b = num.top();
|
|
num.pop();
|
|
|
|
int a = num.top();
|
|
num.pop();
|
|
|
|
char p = stk.top();
|
|
stk.pop();
|
|
|
|
int r;
|
|
|
|
if (p == '+')
|
|
r = a + b;
|
|
else if (p == '-')
|
|
r = a - b;
|
|
else if (p == '*')
|
|
r = a * b;
|
|
else if (p == '/')
|
|
r = a / b;
|
|
|
|
num.push(r);
|
|
}
|
|
|
|
int main() {
|
|
string s;
|
|
cin >> s;
|
|
|
|
for (int i = 0; i < s.size(); i++) {
|
|
if (isdigit(s[i])) {
|
|
int x = 0;
|
|
while (i < s.size() && isdigit(s[i])) {
|
|
x = x * 10 + s[i] - '0';
|
|
i++;
|
|
}
|
|
i--;
|
|
|
|
num.push(x);
|
|
}
|
|
|
|
else if (s[i] == '(')
|
|
stk.push(s[i]);
|
|
|
|
else if (s[i] == ')') {
|
|
while (stk.top() != '(') eval();
|
|
|
|
stk.pop();
|
|
} else {
|
|
while (stk.size() && h[s[i]] <= h[stk.top()]) eval();
|
|
stk.push(s[i]);
|
|
}
|
|
}
|
|
while (stk.size()) eval();
|
|
printf("%d\n", num.top());
|
|
return 0;
|
|
}
|