Cod sursa(job #2946867)

Utilizator andreea_chivuAndreea Chivu andreea_chivu Data 25 noiembrie 2022 11:23:02
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.5 kb
#include <iostream>
#include <fstream>

using namespace std;

#define NMAX 100002

char s[NMAX];
int p = 0;

bool din_sir(char ch){
    if(('0' <= ch && ch <= '9') || ch == '*' || ch == '+' || ch == '-' || ch == '/' || ch == '(' || ch == ')'){
            return true;
    }
    return false;
}

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] == '-'){
        semn = -semn;
        p++;
    }
    if(s[p] == '('){
        p++;
        val = expresie();
        p++;
        return semn * val;
    }
    while('0' <= s[p] && s[p] <= '9'){
        val = val * 10 + (s[p] - '0');
        p++;
    }
    return semn * val;
}


int main()
{
    ifstream fin("evaluare.in");
    ofstream fout("evaluare.out");

    int n = 0;
    char ch;
    fin.get(ch);
    while(din_sir(ch)){
        s[n++] = ch;
        fin.get(ch);
    }

    fout << expresie();

    fin.close();
    fout.close();
    return 0;
}