Cod sursa(job #3371649)

Utilizator Alias47John Doe Alias47 Data 31 octombrie 2026 11:07:57
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.48 kb
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
typedef unsigned long long ull;
typedef vector<int> vc;
typedef vector<vector<int>> matrix;
#define sp ' '
#define ft(n) for(int i=1; i<=n; i++)
string file = "evaluare";
ifstream f(file + ".in");
ofstream g(file + ".out");

int p; //string pos
string s;

int expression(const string& s, int& p);
int term(const string& s, int& p);
int factor(const string& s, int& p);
int number(const string& s, int& p);

int expression(const string& s, int& p)
{
    int res = term(s, p);
    while (p < s.size() && (s[p] == '+' || s[p] == '-'))
    {
        int sign = 1;
        if (s[p] == '-') sign = -1;
        p++;
        res += sign * term(s, p);
    }
    return res;
}
int term(const string& s, int& p)
{
    int res = factor(s, p);
    while (p < s.size() && (s[p] == '*' || s[p] == '/'))
    {
        p++;
        if (s[p - 1] == '*')
            res *= factor(s, p);
        else
            res /= factor(s, p);
    }
    return res;
}
int factor(const string& s, int& p)
{
    if (s[p] == '(')
    {
        p++;
        int res = expression(s, p);
        p++;
        return res;
    }
    else
        return number(s, p);
}
int number(const string& s, int& p)
{
    int res = 0;
    while ('0' <= s[p] && s[p] <= '9')
    {
        res = res * 10 + (s[p] - '0');
        p++;
    }
    return res;
}


int main()
{
    f >> s;
    g << expression(s, p);
    return 0;
}