Cod sursa(job #822220)

Utilizator MciprianMMciprianM MciprianM Data 22 noiembrie 2012 23:50:57
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 0.92 kb
#include <fstream>

using namespace std;

const int MAXN = 100009, MAX_LEVEL = 3;
char s[MAXN];
int cursor;

int getOpLevel(char c) {
	if(c == '+' || c == '-')	return 1;
	if(c == '*' || c == '/')	return 2;
	return 0;
}

int compute(int x, int y, char op) {
	if(op == '+')	return x + y;
	if(op == '-')	return x - y;
	if(op == '*')	return x * y;
	if(op == '/')	return x / y;
	return 0;
}

int eval(int level) {
	int t(0);
	if(level == MAX_LEVEL) {
		if(s[cursor] == '(') {
			++cursor; t = eval(1); ++cursor;
		} else {
			while(isdigit(s[cursor]))
				t = t * 10 + s[cursor++] - '0';
		}
	}
	else {
		t = eval(level + 1);
		while(getOpLevel(s[cursor]) == level) {
			++cursor;
			t = compute(t, eval(level + 1), s[cursor - 1]);
		}
	}
	return t;
}

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