Cod sursa(job #3346610)

Utilizator bandyAndrei Raileanu Szeles bandy Data 14 martie 2026 16:28:02
Problema Evaluarea unei expresii Scor 10
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.37 kb
#include <bits/stdc++.h>

using namespace std;

ifstream in("evaluare.in");
ofstream out("evaluare.out");

string s;
stack<char> op;
stack<int> num;

bool calc(int i) {
    if (s[i]==')') {
        return true;
    }
    if (op.empty()) {
        return false;
    }
    if ((op.top()=='*' || op.top()=='/') && (s[i]=='+' || s[i]=='-')) {
        return true;
    }
    return false;
}

void ex() {
    while (!op.empty() && op.top()!='(') {
        int x = num.top();
        num.pop();
        if (op.top()=='+') {
            num.top()+=x;
        }
        else if (op.top()=='-') {
            num.top()-=x;
        }
        else if (op.top()=='*') {
            num.top()*=x;
        }
        else if (op.top()=='/') {
            num.top()/=x;
        }
        op.pop();
    }
    if (!op.empty())
        op.pop();
}

int eval() {
    int n=0;
    bool nou=true;
    for (int i=0;i<s.size();i++) {
        if (!(s[i]-'0'>=0 && s[i]-'0'<=9)) {
            if (nou==false) {
                num.push(n);
                n=0;
                nou=true;
            }
            if (calc(i)==true) {
                ex();
            }
            if (s[i]!=')')
                op.push(s[i]);
        }
        else {
            n=n*10+s[i]-'0';
            nou=false;
        }
    }
    num.push(n);
    ex();
    return num.top();
}

int main(){
    in>>s;
    out<<eval();
    return 0;
}