Cod sursa(job #3293955)

Utilizator YosifIosif Andrei Stefan Yosif Data 14 aprilie 2025 10:57:01
Problema Evaluarea unei expresii Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 0.99 kb
#include <bits/stdc++.h>
using namespace std;

string fileName = "evaluare";
ifstream fin(fileName + ".in");
ofstream fout(fileName + ".out");

string s;

int element(int &k);
int factor(int &k);
int suma(int &k);

int suma(int &k) {

    int ret = factor(k);

    while (k < s.length() && (s[k] == '+' || s[k] == '-')) {

        k++;
        ret += factor(k);
    }

    return ret;
}

int factor(int &k) {

    int ret = element(k);

    while (k < s.length() && (s[k] == '*' || s[k] == '/')) {

        if (s[k] == '*') {

            k++;
            ret *= element(k);
        }
        else {

            k++;
            ret /= element(k);
        }
    }

    return ret;
}

int element(int &k) {

    int ret = 0;

    if (s[k] == '(') {

        k++;
        ret = suma(k);
        k++;
        return ret;
    }

    while (k < s.length() && isdigit(s[k]))
        ret = ret * 10 + (s[k] - '0'), k++;
    return ret;
}

int main() {

    fin >> s;
    int k = 0;
    fout << suma(k);

    return 0;
}