Cod sursa(job #2672523)

Utilizator domistnSatnoianu Dominic Ioan domistn Data 14 noiembrie 2020 10:18:34
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.76 kb
#include <bits/stdc++.h>

using namespace std;

inline int applyOp(const int X, const int Y, const char OP) {
    if(OP == '+') return X + Y;
    if(OP == '-') return X - Y;
    if(OP == '*') return X * Y;
    return X / Y;
}

inline int opPrec(const char X) {
    if(X == '+' || X == '-') return 1;
    if(X == '*' || X == '/') return 2;
    return 0;
}

int evalExp(const string X) {
    stack<int> nbs;
    stack<char> ops;
    for(int i = 0; i < X.length(); ++i) {
        if(X[i] == ' ') continue;
        if(isdigit(X[i])) {
            int nbc = 0;
            while(i < X.length() && isdigit(X[i]))
                nbc = nbc * 10 + X[i] - '0', ++i;
            --i, nbs.push(nbc);
        } else if(X[i] == '(') {
            ops.push(X[i]);
        } else if(X[i] == ')') {
            while(!ops.empty() && ops.top() != '(') {
                int nb1 = nbs.top(); nbs.pop();
                int nb2 = nbs.top(); nbs.pop();
                char op = ops.top(); ops.pop();
                nbs.push(applyOp(nb2, nb1, op));
            }
            if(!ops.empty()) ops.pop();
        } else {
            while(!ops.empty() && opPrec(X[i]) <= opPrec(ops.top())) {
                int nb1 = nbs.top(); nbs.pop();
                int nb2 = nbs.top(); nbs.pop();
                char op = ops.top(); ops.pop();
                nbs.push(applyOp(nb2, nb1, op));
            }
            ops.push(X[i]);
        }
    }
    while(!ops.empty()) {
        int nb1 = nbs.top(); nbs.pop();
        int nb2 = nbs.top(); nbs.pop();
        char op = ops.top(); ops.pop();
        nbs.push(applyOp(nb2, nb1, op));
    }
    return nbs.top();
}

int main()
{
    string inp = "100*(2+12)/14*0+1-1-5+6";
    cout<<evalExp(inp);
    return 0;
}