Cod sursa(job #1824298)

Utilizator Coroian_DavidCoroian David Coroian_David Data 7 decembrie 2016 17:52:24
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.69 kb
#include <cstdio>

using namespace std;

FILE *f, *g;

char s[100005];

int rez;

int crChar;

int expresie();
int termen();
int factor();

int isSign1(char c)
{
    if(c == '+')
        return 1;

    if(c == '-')
        return -1;

    return 0;
}

bool isSign2(char c)
{
    if(c == '*' || c == '/')
        return true;

    return false;
}

bool isDigit(char c)
{
    if(c >= '0' && c <= '9')
        return true;

    return false;
}

int expresie()
{
    int rez = termen(), sign = 0;

    while((sign = isSign1(s[crChar])) != 0)
        crChar ++, rez += sign * termen();

    return rez;
}

int termen()
{
    int rez = factor();

    while(isSign2(s[crChar]))
    {
        if(s[crChar] == '*')
            crChar ++, rez *= factor();

        if(s[crChar] == '/')
            crChar ++, rez /= factor();
    }

    return rez;
}

int factor()
{
    int rez = 0, sign = 1;

    while(s[crChar] == '-')
    {
        sign *= (-1);

        crChar ++;
    }

    if(s[crChar] == '(')
    {
        crChar ++;

        rez = expresie();

        crChar ++;

       // printf("*%d\n", rez);

        return rez * sign;
    }

    while(isDigit(s[crChar]))
    {
        rez *= 10;

        rez += (s[crChar] - '0');

        crChar ++;
    }

    return sign * rez;
}

void readFile()
{
    f = fopen("evaluare.in", "r");

    fgets(s, 100003, f);

    fclose(f);
}

void solve()
{
    rez = expresie();
}

void printFile()
{
    g = fopen("evaluare.out", "w");

    fprintf(g, "%d\n", rez);

    fclose(g);
}

int main()
{
    readFile();

    solve();

    printFile();

    return 0;
}