Pagini recente » Cod sursa (job #925502) | Cod sursa (job #2644805) | Cod sursa (job #2499694) | Cod sursa (job #499581) | Cod sursa (job #3020332)
#include <bits/stdc++.h>
#define MAXSZ 100005
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
int getOperatorOrder(char op) {
if (op == '*' || op == '/')
return 2;
if (op == '+' || op == '-')
return 1;
return 0;
}
int eval(int a, int b, char op) {
switch (op) {
case '+':
return a + b;
case '-':
return a - b;
case '*':
return a * b;
case '/':
return a / b;
default:
return 0;
}
}
int eval(char expr[]) {
stack<int> operands;
stack<char> operators;
for (int i = 0; expr[i]; i++) {
if (expr[i] >= '0' && expr[i] <= '9') {
int number = 0;
while (expr[i] >= '0' && expr[i] <= '9')
number = number * 10 + (expr[i++] - '0');
i--;
operands.push(number);
} else if (expr[i] == '(') {
operators.push(expr[i]);
} else if (expr[i] == ')') {
while (!operators.empty() && operators.top() != '(') {
char op = operators.top(); operators.pop();
int b = operands.top(); operands.pop();
int a = operands.top(); operands.pop();
operands.push(eval(a, b, op));
}
operators.pop();
} else {
while (
!operators.empty() &&
getOperatorOrder(operators.top()) >= getOperatorOrder(expr[i])
) {
char op = operators.top(); operators.pop();
int b = operands.top(); operands.pop();
int a = operands.top(); operands.pop();
operands.push(eval(a, b, op));
}
operators.push(expr[i]);
}
}
while (!operators.empty()) {
char op = operators.top(); operators.pop();
int b = operands.top(); operands.pop();
int a = operands.top(); operands.pop();
operands.push(eval(a, b, op));
}
return operands.top();
}
int main() {
char expr[MAXSZ];
fin.getline(expr, MAXSZ);
fout << eval(expr);
return 0;
}