complete code in cpp

 avatar
user_9809957
c_cpp
a year ago
1.8 kB
4
Indexable
Never
#include <cstddef>
#include <iostream>
#include <stack>
#include <string>

int operate(int a, int b, char op) {
    if (op == '+') return a + b;
    if (op == '-') return a - b;
    return 0;
}

void compute(std::stack<int>& values, std::stack<char>& operators) {
    int b = values.top(); values.pop();
    int a = values.top(); values.pop();
    char op = operators.top(); operators.pop();
    values.push(operate(a, b, op));
}

int process_exp(const std::string& expr) {
    std::stack<int> values;
    std::stack<char> operators;

    size_t i = 0;
    while (i < expr.size()) {
        if (expr[i] == ' ') {
            i++;
            continue;
        }
        if (isdigit(expr[i])) {
            int val = 0;
            while (i < expr.size() && isdigit(expr[i])) {
                val = val * 10 + (expr[i] - '0');
                i++;
            }
            values.push(val);
        } else if (expr[i] == '+' || expr[i] == '-') {
            while (!operators.empty() && (operators.top() == '+' || operators.top() == '-')) {
                compute(values, operators);
            }
            operators.push(expr[i]);
            i++;
        } else if (expr[i] == '(') {
            operators.push(expr[i]);
            i++;
        } else if (expr[i] == ')') {
            while (operators.top() != '(') {
                compute(values, operators);
            }
            operators.pop();  // Pop the '('
            i++;
        }
    }
    while (!operators.empty()) {
        compute(values, operators);
    }

    return values.top();
}

int main() {
    std::cout << process_exp("1+20") << std::endl;  // 21
    std::cout << process_exp("10-2+40") << std::endl;  // 48
    std::cout << process_exp("10-(1-9)") << std::endl;  // 18

    return 0;
}