Pagini recente » Cod sursa (job #3004446) | Cod sursa (job #159220) | Cod sursa (job #2084375) | Cod sursa (job #397607) | Cod sursa (job #2969613)
#include <bits/stdc++.h>
#define MAXSZ 100000
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char str[MAXSZ + 1];
int semn(int lo, int hi, char s1, char s2) {
for (int i = hi; i >= lo; i--) {
if (str[i] == ')')
return -1;
if (str[i] == s1 || str[i] == s2)
return i;
}
return -1;
}
int numar(int lo, int hi) {
int result = 0;
for (int i = lo; i <= hi; i++)
if (str[i] >= '0' && str[i] <= '9')
result = result * 10 + str[i] - '0';
return result;
}
int eval(int lo, int hi) {
int poz = semn(lo, hi, '+', '-');
if (poz != -1) {
int left = eval(lo, poz - 1);
int right = eval(poz + 1, hi);
if (str[poz] == '+')
return left + right;
else
return left - right;
}
poz = semn(lo, hi, '*', '/');
if (poz != -1) {
int left = eval(lo, poz - 1);
int right = eval(poz + 1, hi);
if (str[poz] == '*')
return left * right;
else
return left / right;
}
if (str[lo] == '(' && str[hi] == ')')
return eval(lo + 1, hi - 1);
return numar(lo, hi);
}
int main() {
fin.getline(str, MAXSZ);
fout << eval(0, (int) strlen(str) - 1);
return 0;
}