Pagini recente » Cod sursa (job #235870) | Cod sursa (job #3294051) | Monitorul de evaluare | Cod sursa (job #3289719) | Cod sursa (job #3294048)
#include <bits/stdc++.h>
using namespace std;
int precedence(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
}
long long applyOp(long long a, long long b, char op) {
switch (op) {
case '+': return a + b;
case '-': return a - b;
case '*': return a * b;
case '/': return a / b;
}
return 0;
}
int main() {
ios::sync_with_stdio(false);
cin.tie(nullptr);
freopen("evaluare.in", "r", stdin);
freopen("evaluare.out", "w", stdout);
string expr;
getline(cin, expr);
stack<char> ops;
vector<string> output;
for (int i = 0; i < (int)expr.size(); i++) {
if (isspace((unsigned char)expr[i])) continue;
if (isdigit((unsigned char)expr[i])) {
long long val = 0;
int start = i;
while (i < (int)expr.size() && isdigit((unsigned char)expr[i])) {
val = val * 10 + (expr[i] - '0');
i++;
}
i--;
output.push_back(to_string(val));
} else if (expr[i] == '(') {
ops.push(expr[i]);
} else if (expr[i] == ')') {
while (!ops.empty() && ops.top() != '(') {
output.push_back(string(1, ops.top()));
ops.pop();
}
if (!ops.empty()) {
ops.pop();
}
} else {
while (!ops.empty() && precedence(ops.top()) >= precedence(expr[i])) {
if (ops.top() == '(') break;
output.push_back(string(1, ops.top()));
ops.pop();
}
ops.push(expr[i]);
}
}
while (!ops.empty()) {
output.push_back(string(1, ops.top()));
ops.pop();
}
stack<long long> st;
for (auto &token : output) {
if (isdigit((unsigned char)token[0]) || (token.size() > 1 && isdigit((unsigned char)token[1]))) {
long long val = stoll(token);
st.push(val);
} else {
long long b = st.top(); st.pop();
long long a = st.top(); st.pop();
long long result = applyOp(a, b, token[0]);
st.push(result);
}
}
long long answer = st.top();
cout << answer << "\n";
return 0;
}