Cod sursa(job #2720010)

Utilizator etohirseCristi Cretu etohirse Data 10 martie 2021 15:21:02
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.85 kb
#include <iostream>
#include <fstream>

std::fstream fin("evaluare.in", std::ios::in);
std::fstream fout("evaluare.out", std::ios::out);

int i;
std::string s;
int eval();
int eval1();
int eval2();

int eval(){
  int rez = eval1();
  while (s[i] == '+' || s[i] == '-'){
    if (s[i] == '+'){
      ++i;
      rez += eval1();
    } else {
      ++i;
      rez -= eval1();
    }
  }

  return rez;
}

int eval1(){
  int rez = eval2();
  while (s[i] == '*' || s[i] == '/'){
    if (s[i] == '*'){
      ++i;
      rez *= eval2();
    } else {
      ++i;
      rez /= eval2();
    }
  }
  
  return rez;
}

int eval2(){
  int rez = 0;

  if (s[i] == '('){
    ++i;
    rez += eval();
    ++i;
  } else {
    while ('0' <= s[i] && s[i] <= '9'){
      rez = rez * 10 + (s[i] - '0');
      ++i;
    }
  }
  return rez;
}

int main(){
  fin >> s;
  fout << eval();
  return 0;
}