Cod sursa(job #3039477)

Utilizator lolismekAlex Jerpelea lolismek Data 28 martie 2023 16:47:00
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.33 kb
#include  <algorithm>
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;

string filename = "evaluare";

#ifdef LOCAL
    ifstream fin("input.in");
    ofstream fout("output.out");
#else
    ifstream fin(filename + ".in");
    ofstream fout(filename + ".out");
#endif


int ind = 0;
string s;

int term1();
int term2();

int eval(){
    int x = term1();
    while(s[ind] == '+' || s[ind] == '-'){
        char ch = s[ind];
        ++ind;
        int y = term1();
        if(ch == '+'){
            x += y;
        }else{
            x -= y;
        }
    }
    return x;
}

int term1(){
    int x = term2();
    while(s[ind] == '*' || s[ind] == '/'){
        char ch = s[ind];
        ++ind;
        int y = term2();
        if(ch == '*'){
            x *= y;
        }else{
            x /= y;
        }
    }
    return x;
}

int term2(){
    int sign = 1;
    while(s[ind] == '-'){
        ++ind;
        sign *= (-1);
    }

    int ans = 0;
    if(s[ind] == '('){
        ++ind;
        ans = eval();
        ++ind;
    }else{
        while('0' <= s[ind] && s[ind] <= '9'){
            ans = ans * 10 + (s[ind] - '0');
            ind++;
        }
    }

    return ans;
}

signed main(){

    fin >> s;

    fout << eval() << '\n';

    return 0;
}