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