Pagini recente » Cod sursa (job #2499854) | Cod sursa (job #3280550) | Profil funkydvd | Cod sursa (job #460501) | Cod sursa (job #947233)
Cod sursa(job #947233)
#include <string>
#include <cstdlib>
#include <fstream>
using namespace std;
string exp;
const string op[] = {"+-", "*/", "^"};
inline int eval(char op, int a, int b)
{
switch(op)
{
case '+' : return a + b;
case '-' : return a - b;
case '*' : return a * b;
case '/' : return a / b;
}
return - (1 << 30);
}
inline bool isNumeric(char x) {return x >= '0' && x <= '9';}
inline int eval(int level, string::iterator& it, const string::iterator& iend)
{
int x;
if(2 == level)
{
if('(' == *it)
{
++it;
x = eval(0, (it), (iend));
++it;
}
else for(x = 0; it != iend && isNumeric(*it); ++it)
x = x * 10 + *it - '0';
}
else for(x = eval(level + 1, (it), (iend)); it != iend && string::npos != op[level].find(*it); )
{
char op = *(it++);
x = eval(op, x, eval(level + 1, (it), (iend)));
}
return x;
}
int main()
{
ifstream in("evaluare.in");
ofstream out("evaluare.out");
getline(in, exp);
string::iterator it = exp.begin();
out << eval(0, it, exp.end());
return EXIT_SUCCESS;
}