Cod sursa(job #276277)

Utilizator peanutzAndrei Homorodean peanutz Data 11 martie 2009 00:38:02
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1 kb
#include <stdio.h>
#include <string.h>

#define NMAX 100010

char a[NMAX];
long n;
long i;


long first();
long second();
long third();


long third()
{
	long res = 0, sgn = 1;
	if(a[i] == '(')
	{
		++i;
		res = first();
		++i;
		return res;
	}

	if(a[i] == '-')
	{
		++i;
		sgn = -1;
	}


	while(i < n && a[i] >= '0' && a[i] <= '9')
		res = res*10 + a[i]-'0', ++i;

	return res * sgn;
}


long second()
{
	long res = third(), sgn;
	while(i < n && (a[i] == '/' || a[i] == '*'))
	{
		if(a[i] == '*')
			++i, res *= third();
		else
			++i, res /= third();
	}
	return res;
}

long first()
{
	long res = second(), sgn;
	while(i < n && (a[i] == '+' || a[i] == '-'))
	{
		if(a[i] == '-')
			sgn = -1;
		else
			sgn = 1;

		++i;
		res += sgn*second();
	}
	return res;
}

int main()
{
	freopen("evaluare.in", "r", stdin);
	freopen("evaluare.out", "w", stdout);

	scanf("%s", a);
	n = strlen(a);
	i = 0;

	printf("%ld\n", first());

	return 0;
}