Cod sursa(job #2848524)

Utilizator zetef3Dediu Stefan zetef3 Data 12 februarie 2022 19:07:20
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.94 kb
#include <fstream>
#include <stack>
#include <string>

using namespace std;

ifstream f("evaluare.in");
ofstream g("evaluare.out");

int exec_operatie(int n1, char o, int n2) {
    switch (o) {
        case '+': return n1 + n2;
        case '-': return n1 - n2;
        case '*': return n1 * n2;
        case '/': return n1 / n2;
        case '%': return n1 % n2;
    }
}

int prioritate(char o) {
    switch (o) {
        case '+':
        case '-':
            return 1;

        case '*':
        case '/':
        case '%':
            return 2;
    }

    return 0;
}

void update_stive(stack<int> &valori, stack<char> &operatori) {
    int n2 = valori.top();      valori.pop();
    char o = operatori.top();   operatori.pop();
    int n1 = valori.top();      valori.pop();

    valori.push(exec_operatie(n1, o, n2));
}

int evaluare(string u_l) {
    stack<int> valori;
    stack<char> operatori;

    for (int i = 0; i<u_l.size(); i++) {
        if (u_l[i] == ' ') continue;

        if (u_l[i] == '(') operatori.push(u_l[i]);
        else if (isdigit(u_l[i])) {
            int nr = 0;
            while (i<u_l.size() && isdigit(u_l[i])) {
                nr = nr * 10 + (u_l[i] - '0');
                i++;
            }
            valori.push(nr);
            i--;
        } else if (u_l[i] == ')') {
            while (operatori.top() != '(') {
                update_stive(valori, operatori);
            }
            operatori.pop();
        } else {
            while (!operatori.empty() && (prioritate(operatori.top()) >= prioritate(u_l[i])) ) {
                update_stive(valori, operatori);
            }
            operatori.push(u_l[i]); //operatorul citit in stiva
        }
    }

    while (!operatori.empty()) {
        update_stive(valori, operatori);
    }

    return valori.top();
}

int main() {
    string expr;
	
	f >> expr;
	g << evaluare(expr);

    return 0;
}