Cod sursa(job #2696057)

Utilizator PoseidonGeminiPoseidonGemini PoseidonGemini Data 15 ianuarie 2021 10:19:42
Problema Evaluarea unei expresii Scor 90
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.63 kb
#include <fstream>
#include <string>

std::ifstream fin("evaluare.in");
std::ofstream fout("evaluare.out");

class ecuatie {
public:
    ecuatie() {
        this->rezultat = 0;
        this->pozitie = 0;
        this->este_rezolvat = 0;
        this->str_ecuatie.clear();
    }

    ecuatie(const char* str) {
        this->rezultat = 0;
        this->pozitie = 0;
        this->este_rezolvat = 0;
        this->str_ecuatie.clear();
        this->str_ecuatie.append(str);
    }

    void schimba_ecuatie(const char* str) {
        this->rezultat = 0;
        this->pozitie = 0;
        this->este_rezolvat = 0;
        this->str_ecuatie.clear();
        this->str_ecuatie.append(str);
    }

    std::size_t rezolva() {
        if (this->este_rezolvat == 0) {
            this->este_rezolvat = 1;
            this->pozitie = 0;
            this->rezultat = eval();
        }
        
        return this->rezultat;
    }

private:
    std::size_t pozitie;
    std::size_t rezultat;
    std::string str_ecuatie;
    bool este_rezolvat;

    std::size_t eval() {
        std::size_t r = termen();

        while (this->str_ecuatie[this->pozitie] == '+' || this->str_ecuatie[this->pozitie] == '-') {
            switch (this->str_ecuatie[this->pozitie]) {
            case '+':
                this->pozitie++;
                r = r + termen();
                break;
            case '-':
                this->pozitie++;
                r = r - termen();
                break;
            }
        }

        return r;
    }

    std::size_t termen()
    {
        std::size_t r = factor();

        while (this->str_ecuatie[this->pozitie] == '*' || this->str_ecuatie[this->pozitie] == '/') {
            switch (this->str_ecuatie[this->pozitie]) {
            case '*':
                this->pozitie++;
                r = r * factor();
                break;

            case '/':
                this->pozitie++;
                r = r / factor();
                break;
            }
        }

        return r;
    }

    std::size_t factor()
    {
        std::size_t r = 0;

        if (this->str_ecuatie[this->pozitie] == '(')
        {
            this->pozitie++;
            r = eval();
            this->pozitie++;
        }
        else {
            while (this->str_ecuatie[this->pozitie] >= '0' && this->str_ecuatie[this->pozitie] <= '9')
            {
                r = r * 10 + (std::size_t)(this->str_ecuatie[this->pozitie]) - (std::size_t)('0');
                this->pozitie++;
            }
        }

        return r;
    }
        
};

std::string str;

int main() {
    std::getline(fin, str);
    fout << ecuatie(str.c_str()).rezolva() << '\n';
    return 0;
}