Cod sursa(job #2514750)

Utilizator kokitchyAlastor kokitchy Data 26 decembrie 2019 18:52:34
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.89 kb
#include <fstream>
#include <cstring>

char operand[4][4] = {"+-", "*/", "^", ""};
char s[100010];
char* p = s;
const long hmax = 2;

long operatie(long x, long y, char c) {
	switch (c) {
	case '+': 
		return x + y;
		break;
	case '-':
		return x - y;
		break;
	case '*':
		return x * y;
		break;
	case '/':
		return x / y;
	}

	return 0;
}

long eval(long);

long element() {
	long r = 0;
	if (*p == '(') {
		++p;
		r = eval(0);
		++p;
	}
	else {
		while (strchr("0123456789", *p))
			r = r * 10 + *(++p - 1) - '0';
	}

	return r;
}

long eval(long h) {
	long r = (h == hmax) ? element() : eval(h + 1);

	while (strchr(operand[h], *p))
		r = operatie(r, eval(h + 1), *(++p - 1));

	return r;
}

int main()
{
	std::ifstream fin("evaluare.in");
	std::ofstream fout("evaluare.out");

	fin >> s;
	fout << eval(0);

	fin.close(), fout.close();

	return 0;
}