Cod sursa(job #1722521)

Utilizator meriniucrMeriniuc Razvan- Dumitru meriniucr Data 28 iunie 2016 12:25:00
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
// http://www.infoarena.ro/problema/evaluare

#include <cstdio>

const int   MAX_LENGTH = 100001;
char        str[MAX_LENGTH];
const char* pStr = str;

long
termen();

long
factor();

long
eval()
{
    long res;

    res = termen();
    while ( (*pStr == '+') or
            (*pStr == '-') )
    {
        if (*pStr == '+')
        {
            pStr++;
            res += termen();
        }
        else
        {
            pStr++;
            res -= termen();
        }
    }

    return res;
}

long
termen()
{
    long res;

    res = factor();
    while ( (*pStr == '*') or
            (*pStr == '/') )
    {
        if (*pStr == '*')
        {
            pStr++;
            res *= factor();
        }
        else
        {
            pStr++;
            res /= factor();
        }
    }

    return res;
}

long
factor()
{
    long res;

    res = 0;
    if (*pStr == '(')
    {
        pStr++;
        res = eval();
        pStr++; // Jumps over the closing bracket
    }
    else
    {
        while ( (*pStr >= '0') and
                (*pStr <= '9') )
        {
            res = res * 10 + *pStr - '0';
            pStr++;
        }
    }

    return res;
}

int main()
{
    fgets(str, MAX_LENGTH, fopen("evaluare.in", "r"));
    fprintf(fopen("evaluare.out", "w"), "%ld\n", eval());

    return 0;
}