Cod sursa(job #2774901)

Utilizator caesar2001Stoica Alexandru caesar2001 Data 13 septembrie 2021 13:57:14
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.87 kb
#include <bits/stdc++.h>
#define ll long long
#define lsb(x) x & -x

using namespace std;

int getPriority(char c) {
    if(c == '+' || c == '-')
        return 1;
    if(c == '*' || c == '/')
        return 2;
    return 0;
}

int getResult(int a, int b, char op) {
    if(op == '+')
        return a + b;
    if(op == '-')
        return a - b;
    if(op == '/')
        return a / b;
    if(op == '*')
        return a * b;
}

void compute(stack<int> &values, stack<char> &operators) {
    int a = values.top();
    values.pop();
    int b = values.top();
    values.pop();

    int result = getResult(b, a, operators.top());
    operators.pop();

    values.push(result);
}

int getNumber(int &index, const string &s) {
    int number = 0;
    while(index < s.size() && '0' <= s[index] && s[index] <= '9') {
        number *= 10;
        number += (s[index] - '0');
        index ++;
    }
    return number;
}

int main() {
    ifstream cin("evaluare.in");
    ofstream cout("evaluare.out");

    string s;
    cin >> s;

    stack<char> operators;
    stack<int> values;

    int index = 0;
    while(index < s.size()) {
        if('0' <= s[index] && s[index] <= '9')
            values.push(getNumber(index, s));
        else if(s[index] == '(') {
            operators.push(s[index]);
            index ++;
        } else if(s[index] == ')') {
            while(operators.top() != '(')
                compute(values, operators);
            operators.pop();
            index ++;
        } else if(getPriority(s[index]) > 0) {
            while(operators.size() && getPriority(operators.top()) > 0 && getPriority(s[index]) <= getPriority(operators.top())) {
                compute(values, operators);
            }
            operators.push(s[index]);
            index ++;
        }
    }

    while(operators.size())
        compute(values, operators);

    cout << values.top();

    return 0;
}