Cod sursa(job #2871942)

Utilizator andriciucandreeaAndriciuc Andreea andriciucandreea Data 16 martie 2022 02:13:13
Problema Evaluarea unei expresii Scor 0
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 2.22 kb
#include <iostream>
#include <cstring>
#include <stack>

using namespace std;

int order(char opr)
{

    if(opr == '+' || opr == '-')
        return 1;
    if(opr == '*' || opr == '/')
        return 2;
    return 0;
}

int operation(int x, int y, char opr)
{
    if(opr == '+')
        return x+y;
    if(opr == '-')
        return x-y;
    if(opr == '*')
        return x*y;
    if(opr == '/')
        return x/y;
}

int solve(string str)
{
    int i, len = str.length(),x, y, partial_res = 0, nr= 0 ;
    char op;
    stack <int> val;
    stack <char> oprs;
    for (i=0; i<len; i++)
    {
        if(isdigit(str[i]))
        {
            nr = 0;
            while(i<len && isdigit(str[i]))
            {
                nr *= 10;
                nr += (str[i] - '0');
                i++;
            }
            i--;
            val.push(nr);
        }
        else if(str[i] == ')')  ///am intalnit o paranteza inchisa, deci trebuie sa rezolvam tot ce avem in paranteza din momentul in care s-a deschis
        {
            while(!oprs.empty() && oprs.top() != '(')
            {
                op = oprs.top();
                oprs.pop();
                y = val.top();
                val.pop();
                x = val.top();
                val.pop();
                partial_res = operation(x, y, op);
                val.push(partial_res);
            }
            oprs.pop();

        }
        else
        {
            while(!oprs.empty() && order(oprs.top()) >= order(str[i]))
            {
                op = oprs.top();
                oprs.pop();
                y = val.top();
                val.pop();
                x = val.top();
                val.pop();
                partial_res = operation(x, y, op);
                val.push(partial_res);
            }
            oprs.push(str[i]);
        }

    }

    while(!oprs.empty())
    {
        op = oprs.top();
        oprs.pop();
        y = val.top();
        val.pop();
        x = val.top();
        val.pop();
        partial_res = operation(x, y, op);
        val.push(partial_res);
    }
    return val.top();
}

int main()
{
    cout << solve("(1+1)*13+10/2");
    return 0;
}