Pagini recente » Borderou de evaluare (job #3367485) | Borderou de evaluare (job #3367478) | Cod sursa (job #3367478) | Cod sursa (job #3367484) | Cod sursa (job #3367487)
#include <iostream>
#include <cstring>
using namespace std;
#define MAXS 100000
char s[MAXS];
int sIndex;
int n;
char operatii[MAXS];
int opIndex;
int factori[MAXS];
int factIndex;
int factor(){
int nr = 0;
while(s[sIndex] >= '0' && s[sIndex] <= '9'){
nr = nr * 10 + s[sIndex] - '0';
sIndex++;
}
return nr;
}
int priority(char op){
if(op == '*' || op == '/'){
return 2;
}
if(op == '+' || op == '-'){
return 1;
}
return 0;
}
int compute(int a, int b, char op){
int rez = 0;
if(op == '+'){
rez = a + b;
}
if(op == '-'){
rez = a - b;
}
if(op == '*'){
rez = a * b;
}
if(op == '/'){
rez = a / b;
}
return rez;
}
void pushOperator(char op){
if(op == '+' || s[sIndex] == '-' || op == '*' || op == '/'){
operatii[opIndex++] = op;
}
}
void pushFactor(int nr){
factori[factIndex++] = nr;
}
bool isOpEmpty(){
return opIndex > 0;
}
bool isFactEmpty(){
return factIndex > 0;
}
char popOperator(){
if(isOpEmpty()){
return 0;
}
return operatii[--opIndex];
}
int popFactor(){
if(isFactEmpty()){
return 0;
}
return factori[--factIndex];
}
char topOperator(){
return operatii[opIndex - 1];
}
int topFactor(){
return factori[factIndex - 1];
}
void computeLast(){
int a, b;
a = popFactor();
b = popFactor();
pushFactor(compute(a, b, popOperator()));
}
int main()
{
FILE *fin, *fout;
fin = fopen("evaluare.in", "r");
fout = fopen("evaluare.out", "w");
fgets(s, MAXS, fin);
n = strlen(s);
sIndex = 0;
while(sIndex < n){
if(s[sIndex] >= '0' && s[sIndex] <= '9'){
pushFactor(factor());
}
else if(s[sIndex] == '('){
pushOperator(s[sIndex++]);
}
else if(s[sIndex] == ')'){
while(topOperator() != '('){
computeLast();
}
popOperator();
sIndex++;
}
else if(priority(s[sIndex])){
while(priority(topOperator()) && priority(s[sIndex]) <= priority(topOperator())){
computeLast();
}
pushOperator(s[sIndex++]);
}
else{
sIndex++;
}
}
while(!isOpEmpty()){
computeLast();
}
fprintf(fout, "%d", popFactor());
fclose(fin);
fclose(fout);
return 0;
}