Cod sursa(job #2923526)

Utilizator livliviLivia Magureanu livlivi Data 15 septembrie 2022 12:15:07
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.19 kb
#include <fstream>
#include <string>

using namespace std;

int expresie(const char* s, int& p);
int termen(const char* s, int& p);
int factor(const char* s, int& p);
int numar(const char* s, int& p);

int expresie(const char* s, int& p) {
	int result = termen(s, p);
	while (s[p] == '+' || s[p] == '-') {
		int sign = (s[p] == '+' ? 1 : -1);
		p++;
		result += sign * termen(s, p);
	}
	return result;
}

int termen(const char* s, int& p) {
	int result = factor(s, p);
	while (s[p] == '*' || s[p] == '/') {
		bool div = (s[p] == '/');
		p++;
		int aux = factor(s, p);
		if (div) {
			result /= aux;
		} else {
			result *= aux;
		}
	}
	return result;
}

int factor(const char* s, int& p) {
	int result = 0;
	if (s[p] == '(') {
		p++;
		result = expresie(s, p);
		p++;
	} else {
		result = numar(s, p);
	}
	return result;
}

int numar(const char* s, int& p) {
	int sign = 1;
	if (s[p] == '-') {
		sign = -1;
		p++;
	}

	int result = 0;
	while (s[p] >= '0' && s[p] <= '9') {
		result = result * 10 + s[p] - '0';
		p++;
	}

	return sign * result;
}

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

	string s; in >> s;
	int p = 0;
	out << expresie(s.c_str(), p) << endl;
	return 0;
}