Cod sursa(job #735587)

Utilizator BitOneSAlexandru BitOne Data 16 aprilie 2012 20:36:39
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.11 kb
#include <string>
#include <fstream>
#include <cstdlib>

using namespace std;

const int ERROR=-(1<<29);

string exp;
string::const_iterator it, iend;
const string op[]={ "+-", "*/", "^" };

inline int eval(int a, int b, char op)
{
    switch(op)
    {
        case '+' : return a+b;
        case '-' : return a-b;
        case '*' : return a*b;
        case '/' : return a/b;
        default  : return ERROR;
    }
}
inline int eval(int level)
{
    int x;
    char p;
    if(2 == level)
    {
        if('(' == *it)
        {
            ++it;
            x=eval(0);
            ++it;
        }
        else for(x=0; it < iend && *it >= '0' && *it <= '9'; ++it)
                x=x*10+*it-'0';
    }
    else for(x=eval(level+1); it < iend && string::npos != op[level].find(*it); )
         {
            p=*it; ++it;
            x=eval(x, eval(level+1), p);
         }

    return x;
}
int main()
{
    ifstream in( "evaluare.in");
    ofstream out( "evaluare.out" );

    getline(in, exp);
    it=exp.begin(), iend=exp.end();
    out<<eval(0)<<'\n';

    return EXIT_SUCCESS;
}