Pagini recente » Cod sursa (job #3129069) | Cod sursa (job #467845) | Cod sursa (job #72636) | Cod sursa (job #788745) | Cod sursa (job #2870071)
#include <bits/stdc++.h>
using namespace std;
string s;
stack < int > values;
stack < char > ops;
int prec(char c) {
if (c == '+' || c == '-') {
return 1;
}
if (c == '*' || c == '/') {
return 2;
}
return 0;
}
int apply(int val1, int val2, char op) {
switch (op) {
case '+':
return val1 + val2;
case '-':
return val1 - val2;
case '*':
return val1 * val2;
case '/':
return val1 / val2;
default:
return 0;
}
return 0;
}
int eval() {
for (int i = 0; i < s.size(); i++) {
char c = s[i];
if (c == '(') {
ops.push(c);
} else if (c == ')') {
while (!ops.empty() && ops.top() != '(') {
int val2 = values.top();
values.pop();
int val1 = values.top();
values.pop();
char op = ops.top();
ops.pop();
values.push(apply(val1, val2, op));
}
ops.pop();
} else if (isdigit(c)) {
int value = 0;
while (i < s.size() && isdigit(c)) {
value = value * 10 + c - '0';
i++;
c = s[i];
}
values.push(value);
i--;
} else {
while (!ops.empty() && prec(ops.top()) >= prec(c)) {
int val2 = values.top();
values.pop();
int val1 = values.top();
values.pop();
char op = ops.top();
ops.pop();
values.push(apply(val1, val2, op));
}
ops.push(c);
}
}
while (!ops.empty()) {
int val2 = values.top();
values.pop();
int val1 = values.top();
values.pop();
char op = ops.top();
ops.pop();
values.push(apply(val1, val2, op));
}
return values.top();
}
int main(){
ifstream cin("evaluare.in");
ofstream cout("evaluare.out");
cin >> s;
cout << eval();
return 0;
}