Cod sursa(job #821785)

Utilizator MciprianMMciprianM MciprianM Data 22 noiembrie 2012 17:39:50
Problema Evaluarea unei expresii Scor 0
Compilator cpp Status done
Runda Arhiva educationala Marime 1.29 kb
#include <fstream>
#include <cctype>
#include <cassert>

using namespace std;

const int MAXN = 100009;
char s[MAXN];
int cursor;

int eval();

int getNr() {
    int t(0);
    while(isdigit(s[cursor])) {
        t = t * 10 + s[cursor] - '0';
        ++cursor;
    }
    return t;
}

int getExp2() {
    if(isDigit(s[cursor]) {
        return getNr();
    }
}

int getExp() {
    int t(0);
    if(s[cursor] == '(') {
       ++cursor;
       t = eval();
       ++cursor;
    }
    else {
        t = getNr();
        while(s[cursor] == '*' || s[cursor] == '/') {
            if(s[cursor] == '*') {
                ++cursor;
                t *= getExp2();
            }
            else {
                ++cursor;
                t /= getExp2();
            }
        }
    }
    return t;
}

int eval() {
    int t = getExp();
    while(s[cursor] == '-' || s[cursor] == '+') {
        if(s[cursor] == '-') {
            ++cursor;
            t -= getExp();
        }
        else {
            ++cursor;
            t += getExp();
        }
    }
    return t;
}

int main() {
    ifstream f("evaluare.in");
    ofstream g("evaluare.out");
    f >> s;
    int ans = eval();
    g << ans << endl;
    f.close();
    g.close();
    return 0;
}