Cod sursa(job #677865)

Utilizator Bit_MasterAlexandru-Iancu Caragicu Bit_Master Data 10 februarie 2012 19:13:07
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.45 kb
#include <cstdio>

const int L_S_MAX = 100010;

char s[L_S_MAX];

int eval(int&);
int termen(int&);
int factor(int&);

int eval(int &poz) //caracterul final null nu este caracter valid si va fi ignorat
{
    int x = termen(poz);
    int y;
    while(s[poz] == '+' || s[poz] == '-')
        if(s[poz] == '+')
        {
            ++poz;
            y = termen(poz);
            x += y;
        }
        else
        {
            ++poz;
            y = termen(poz);
            x -= y;
        }
    return x;
}

int termen(int &poz)
{
    int x = factor(poz);
    int y;
    while (s[poz] == '*' || s[poz] == '/')
        if (s[poz] == '*')
        {
            ++poz;
            y = factor(poz);
            x *= y;
        }
        else
        {
            ++poz;
            y = factor(poz);
            x /= y;
        }
    return x;
}

int factor(int &poz)//acesta este deja un numar deoarece factorul nu mai poate fi compus din altceva decat un numar (sau o paranteza)
{
    int x = 0;
    if (s[poz] == '(')
    {
        ++poz;
        x = eval(poz);
        ++poz; //peste ')'
        return x;
    }
    while ('0' <= s[poz] && s[poz] <= '9')
    {
        x = x * 10 + s[poz] - '0';
        ++poz;
    }
    return x;
}

int main()
{
    int poz=0;
    freopen("evaluare.in","r",stdin);
    freopen("evaluare.out","w",stdout);
    gets(s);
    printf("%d",eval(poz));
    return 0;
}