Cod sursa(job #2722049)

Utilizator MadalinaKopaczMadalina Kopacz MadalinaKopacz Data 12 martie 2021 16:09:55
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>
#define N 100000
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");

char s[N+1];
int p;  ///current position
int n;

///the functions that we will use
int Factor();
int Exp();
int Term();


int Factor()
{
  int sign = 1, value = 0;
  if(s[p] == '-') p++, sign = -sign;
  if(s[p] == '(')   ///if there is another expression between parenthesis
    {
        p++;
        value = Exp();  ///than calculate that expression
        p++;   ///skip the closed parenthesis
        return sign * value;
    }
  while(isdigit(s[p])) value = value * 10 + ( s[p++] - '0' );  ///if there is just a number, than calculate its value
  return sign * value;
}


int Term()
{
  int res2 = Factor();  ///searching for the first next highest priority opperation of the given expression
  while( s[p] == '*' || s[p] == '/' )
    if(s[p] == '*') p++, res2 *= Factor();   ///multiply
    else  p++, res2 /= Factor();   ///divide
  return res2;
}


int Exp()
{
  int res1 = Term();   ///searching for the first next highest priority opperation of the given expression
  while (s[p] == '+' || s[p] == '-')
       if(s[p] == '+')  p++, res1 += Term();  ///sum
       else     p++, res1 -= Term();    ///subtraction
  return res1;
}

int main()
{
    fin >> s;
    n = strlen(s);
    fout << Exp();
    return 0;
}