Cod sursa(job #2871944)

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

using namespace std;

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

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(), nr= 0 ;
    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 = nr*10 + str[i] - '0';
                i++;
            }
            i--;
            val.push(nr);
            continue;
        }
        if(str[i] == '(')
        {
            oprs.push(str[i]);
            continue;
        }
        if(str[i] == ')')
        {
            while(!oprs.empty() && oprs.top() != '(')
            {
                int x, y, partial_res;
                char op;
                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();
            continue;

        }
        if(strchr("+-/*", str[i]))
        {
            while(!oprs.empty() && order(oprs.top()) >= order(str[i]))
            {
                int x, y, partial_res;
                char op;
                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())
    {
        int x, y, partial_res;
        char op;
        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()
{
    string to_solve;
    fin>>to_solve;
    fout<<solve(to_solve);
    return 0;
}