Pagini recente » Cod sursa (job #2916515) | Cod sursa (job #2702180) | Cod sursa (job #684276) | Cod sursa (job #428342) | Cod sursa (job #2803978)
#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);
}