Cod sursa(job #821766)

Utilizator MciprianMMciprianM MciprianM Data 22 noiembrie 2012 17:26:11
Problema Evaluarea unei expresii Scor 50
Compilator cpp Status done
Runda Arhiva educationala Marime 1.03 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);
    if(s[cursor] == '(') {
       ++cursor;
       t = eval();
       ++cursor;
    }
    else {
        while(isdigit(s[cursor])) {
            t = t * 10 + s[cursor] - '0';
            ++cursor;
        }
    }
    return t;
}

int eval() {
    int t = getNr();
    while(s[cursor] == '*' || s[cursor] == '/') {
        if(s[cursor] == '*') {
            ++cursor;
            t *= getNr();
        }
        else {
            ++cursor;
            t /= getNr();
        }
    }
    while(s[cursor] == '-') {
        ++cursor;
        t -= getNr();
    }
    if(s[cursor] == '+') {
        ++cursor;
        t += eval();
    }
    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;
}