Cod sursa(job #2803978)

Utilizator cezar_titianuTitianu Cezar cezar_titianu Data 20 noiembrie 2021 17:53:50
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.42 kb
#include <fstream>
#include <string>

int getSum(int, int, std::string&);

int getNum(int pos1, int pos2, std::string& str) {
	int ans = 0;
	if (str[pos1] == '(') {
		ans = getSum(pos1 + 1, pos2 - 1, str);
	}
	else {
		for (; pos1 < pos2; pos1++) {
			ans = ans * 10 + str[pos1] - '0';
		}
	}
	return ans;
}

int getProd(int pos1, int pos2, std::string& str) {
	int pos3 = pos1, ans = 1, par = 0;
	bool sign = true;
	while (pos1 < pos2) {
		while (par || (str[pos3] != '*' && str[pos3] != '/' && pos3 != pos2)) {
			if (str[pos3] == '(') {
				par++;
			}
			if (str[pos3] == ')') {
				par--;
			}
			pos3++;
		}
		if (sign) {
			ans *= getNum(pos1, pos3, str);
		}
		else {
			ans /= getNum(pos1, pos3, str);
		}
		sign = ((str[pos3] == '*') ? true : false);
		pos3++;
		pos1 = pos3;
	}
	return ans;
}

int getSum(int pos1, int pos2, std::string& str) {
	int pos3 = pos1, ans = 0, par = 0;
	int sign = 1;
	while (pos1 < pos2) {
		while (par || (str[pos3] != '+' && str[pos3] != '-' && pos3 != pos2)) {
			if (str[pos3] == '(') {
				par++;
			}
			if (str[pos3] == ')') {
				par--;
			}
			pos3++;
		}
		ans += sign * getProd(pos1, pos3, str);
		sign = ((str[pos3] == '+') ? 1 : -1);
		pos3++;
		pos1 = pos3;
	}
	return ans;
}

int main() {
	std::ifstream fin("evaluare.in");
	std::ofstream fout("evaluare.out");
	std::string str;
	fin >> str;
	fout << getSum(0, str.size(), str);
}