Pagini recente » Cod sursa (job #242903) | Borderou de evaluare (job #472007) | Cod sursa (job #1046796) | Cod sursa (job #721701) | Cod sursa (job #3276762)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
stack<int> operands; // Stiva pentru numere
stack<char> operators; // Stiva pentru operatori
// Functie ce returneaza precedenta operatorului
int precedence(char op) {
if (op == '+' || op == '-') return 1;
if (op == '*' || op == '/') return 2;
return 0;
}
// Aplica operatia de varf dintre doi operanzi si returneaza rezultatul
int applyOperation(int a, int b, char op) {
if (op == '+') return a + b;
if (op == '-') return a - b;
if (op == '*') return a * b;
if (op == '/') return a / b; // Impartire intreaga
return 0;
}
// Evalueaza expresia
int evaluate(string &expr) {
int n = expr.size();
for (int i = 0; i < n; i++) {
char ch = expr[i];
if (isdigit(ch)) {
int num = 0;
while (i < n && isdigit(expr[i])) {
num = num * 10 + (expr[i] - '0');
i++;
}
i--; // Revenim un pas inapoi după ultima cifră
operands.push(num);
}
else if (ch == '(') {
operators.push(ch);
}
else if (ch == ')') {
while (!operators.empty() && operators.top() != '(') {
int b = operands.top(); operands.pop();
int a = operands.top(); operands.pop();
char op = operators.top(); operators.pop();
operands.push(applyOperation(a, b, op));
}
operators.pop(); // Eliminăm '('
}
else { // Operator +, -, *, /
while (!operators.empty() && precedence(operators.top()) >= precedence(ch)) {
int b = operands.top(); operands.pop();
int a = operands.top(); operands.pop();
char op = operators.top(); operators.pop();
operands.push(applyOperation(a, b, op));
}
operators.push(ch);
}
}
// Aplicăm operatorii rămași
while (!operators.empty()) {
int b = operands.top(); operands.pop();
int a = operands.top(); operands.pop();
char op = operators.top(); operators.pop();
operands.push(applyOperation(a, b, op));
}
return operands.top();
}
int main() {
string expr;
fin >> expr;
fout << evaluate(expr) << endl;
return 0;
}