Cod sursa(job #1831270)

Utilizator CalarisPredut Denis Stefanita Calaris Data 17 decembrie 2016 18:37:19
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.17 kb
#include <fstream>
#include <string>
#include <iostream>

std::fstream f("evaluare.in",std::ios::in);
std::ofstream g("evaluare.out");

std::string st;

long index = 0;

long solve();
long tr();
long fn();


int main()
{
    long nr;
    f>>st;
    nr = solve();

    g<<nr;
    return 0;
}

long solve()
{
  long x = tr();

  while(st[index] == '+' || st[index] == '-')
    {
      if(st[index] == '+')
        {
        ++index;
        x+=tr();
        }
      if(st[index] == '-')
        {
        ++index;
        x-=tr();
        }
    }

    return x;
}

long tr()
{
  long x = fn();

  while(st[index] == '*' || st[index] == '/')
    {
      if(st[index] == '*')
        {
        ++index;
        x*=fn();
        }
      if(st[index] == '/')
        {
        ++index;
        x/=fn();
        }
    }

    return x;
}

long fn()
{
  long x = 0;
  if(st[index] =='(')
        {
        ++index;
        x = solve();
        ++index;
        }
  else
    {
    while(st[index]>='0' && st[index]<='9')
        {
        x = x*10+ long(st[index]-'0');
        ++index;
        }
    }

  return x;
}