Cod sursa(job #2247048)

Utilizator preda.andreiPreda Andrei preda.andrei Data 27 septembrie 2018 20:26:45
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.46 kb
#include <cctype>
#include <fstream>
#include <string>

using namespace std;

int Eval(const string &str, size_t &pos);

int GetNumber(const string &str, size_t &pos)
{
    if (str[pos] == '(') {
        pos += 1;
        auto num = Eval(str, pos);
        pos += 1;
        return num;
    }

    auto num = 0;
    while (pos < str.size() && isdigit(str[pos])) {
        num = num * 10 + str[pos] - '0';
        pos += 1;
    }
    return num;
}

int MultDiv(const string &str, size_t &pos)
{
    auto prod = GetNumber(str, pos);
    while (pos < str.size() && (str[pos] == '*' || str[pos] == '/')) {
        auto is_mult = str[pos] == '*';
        pos += 1;

        auto other = GetNumber(str, pos);
        if (is_mult) {
            prod *= other;
        } else {
            prod /= other;
        }
    }
    return prod;
}

int AddSub(const string &str, size_t &pos)
{
    auto sum = MultDiv(str, pos);
    while (pos < str.size() && (str[pos] == '+' || str[pos] == '-')) {
        auto is_plus = str[pos] == '+';
        pos += 1;

        auto other = MultDiv(str, pos);
        sum += other * (is_plus ? 1 : -1);
    }
    return sum;
}

int Eval(const string &str, size_t &pos)
{
    return AddSub(str, pos);
}

int Eval(const string &str)
{
    size_t pos = 0;
    return Eval(str, pos);
}

int main()
{
    ifstream fin("evaluare.in");
    ofstream fout("evaluare.out");

    string str;
    getline(fin, str);

    auto res = Eval(str);
    fout << res << "\n";

    return 0;
}