Cod sursa(job #1813036)

Utilizator vladsftVlad Safta vladsft Data 22 noiembrie 2016 17:43:35
Problema Evaluarea unei expresii Scor 100
Compilator cpp Status done
Runda Arhiva educationala Marime 1.02 kb
#include <fstream>
using namespace std;
ifstream in("evaluare.in");
ofstream out("evaluare.out");
const int N=100001;
int p;
char s[N];
int expresie();
int termen();
int factor();
int expresie(){
    int sum=termen();
    while (s[p]=='+'||s[p]=='-')
    {
      if (s[p]=='+'){
        p++;
        sum+=termen();}
      else {
        p++;
        sum-=termen();
      }
    }
    return sum;
}
int termen(){
    int prod=factor();
    while (s[p]=='*'||s[p]=='/')
    {
      if (s[p]=='*'){
        p++;
        prod*=factor();
      }
      else {
        p++;
        prod/=factor();
      }
    }
    return prod;
}
int factor (){
    int val=0, semn=1;
    while (s[p]=='-'){
        p++;
        semn=-semn;
    }
    if (s[p]=='('){
        p++;
        val=expresie();
        p++;
        return semn*val;
    }
    while (s[p]>='0'&&s[p]<='9'){
        val=val*10+(s[p]-'0');
        p++;
    }
    return semn*val;
}
int main()
{
    in.getline(s,N);
    out<<expresie()<<"\n";
    in.close();
    out.close();
    return 0;
}