Pagini recente » Cod sursa (job #1968828) | Cod sursa (job #2181011) | Cod sursa (job #179162) | Cod sursa (job #1975533) | Cod sursa (job #3203084)
#include <bits/stdc++.h>
#define MAXSZ 100000
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
string expr;
int getOrder(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(string& expr) {
stack<int> operands;
stack<char> operators;
for (int i = 0; i < expr.size(); i++) {
if (expr[i] >= '0' && expr[i] <= '9') {
int num = 0;
while (i < expr.size() && expr[i] >= '0' && expr[i] < '9')
num = num * 10 + (int) (expr[i++] - '0');
i--;
operands.push(num);
} else {
switch (expr[i]) {
case '(':
operators.push(expr[i]);
break;
case ')':
while (operators.top() != '(') {
int b = operands.top(); operands.pop();
int a = operands.top(); operands.pop();
char op = operators.top(); operators.pop();
operands.push(eval(a, b, op));
}
operators.pop();
break;
default:
while (!operators.empty() && getOrder(operators.top()) >= getOrder(expr[i])) {
int b = operands.top(); operands.pop();
int a = operands.top(); operands.pop();
char op = operators.top(); operators.pop();
operands.push(eval(a, b, op));
}
operators.push(expr[i]);
break;
}
}
}
while (!operators.empty()) {
int b = operands.top(); operands.pop();
int a = operands.top(); operands.pop();
char op = operators.top(); operators.pop();
operands.push(eval(a, b, op));
}
return operands.top();
}
int main() {
getline(fin, expr);
fout << eval(expr);
return 0;
}