Cod sursa(job #3165000)

Utilizator andreiomd1Onut Andrei andreiomd1 Data 4 noiembrie 2023 22:55:27
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.36 kb
#include <fstream>
#include <string>
#include <deque>

using namespace std;

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

static inline int eval();
static inline int term();
static inline int factor();

deque<char> D;

static inline int eval()
{
    int ans = term();

    while (!D.empty() && (D.front() == '+' || D.front() == '-'))
    {
        if (D.front() == '+')
            D.pop_front(), ans += term();
        else
            D.pop_front(), ans -= term();
    }

    return ans;
}

static inline int term()
{
    int ans = factor();

    while (!D.empty() && (D.front() == '*' || D.front() == '/'))
    {
        if (D.front() == '*')
            D.pop_front(), ans *= factor();
        else
            D.pop_front(), ans /= factor();
    }

    return ans;
}

static inline int factor()
{
    if (D.empty())
        return 1;

    if (D.front() == '(')
    {
        D.pop_front();

        int ans = eval();

        D.pop_front();

        return ans;
    }

    int sign = +1, ans = 0;

    if (D.front() == '-')
        sign = -1, D.pop_front();

    while (!D.empty() && (D.front() >= '0' && D.front() <= '9'))
        ans = ans * 10 + (int)(D.front() - '0'), D.pop_front();

    return (ans * sign);
}

int main()
{
    f.tie(nullptr);

    string S = "";
    f >> S;

    for (auto &it : S)
        D.push_back(it);

    g << eval() << '\n';

    return 0;
}