Cod sursa(job #2962864)

Utilizator MihneaStoicaMihnea Teodor Stoica MihneaStoica Data 9 ianuarie 2023 17:33:48
Problema Evaluarea unei expresii Scor 100
Compilator cpp-64 Status done
Runda Arhiva educationala Marime 1.67 kb
#include <fstream>
#include <stack>

using namespace std;

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

int oper (int a, int b, char op)
{
	switch (op)
	{
		case '+': return a + b;

		case '-': return a - b;

		case '*': return a * b;

		case '/': return a / b;

		default: return NULL;
	}
}

int prec (char op)
{
	if (op == '+' || op == '-')
	{
		return 1;
	}

	if (op == '*' || op == '/')
	{
		return 2;
	}

	return 0;
}

int res (string s)
{
	int i;
	stack<int> vals;
	stack<char> op;

	for (i = 0; i < s.size(); i ++)
	{
		if (s[i] == ' ')
		{
			continue;
		}
		else if (s[i] == '(')
		{
			op.push (s[i]);
		}
		else if (isdigit (s[i]))
		{
			int val = 0;

			while (i < s.size() && isdigit (s[i]))
			{
				val = val * 10 + (s[i ++] - 48);
			}

			vals.push (val);
			i --;
		}
		else if (s[i] == ')')
		{
			while (!op.empty() && op.top() != '(')
			{
				int val2 = vals.top(); vals.pop();
				int val1 = vals.top(); vals.pop();
				char opp = op.top(); op.pop();
				vals.push (oper (val1, val2, opp));
			}

			if (!op.empty())
			{
				op.pop();
			}
		}
		else
		{
			while (!op.empty() && prec (op.top()) >= prec (s[i]))
			{
				int val2 = vals.top(); vals.pop();
				int val1 = vals.top(); vals.pop();
				char opp = op.top(); op.pop();
				vals.push (oper (val1, val2, opp));
			}

			op.push (s[i]);
		}
	}

	while (!op.empty())
	{
		int val2 = vals.top(); vals.pop();
		int val1 = vals.top(); vals.pop();
		char opp = op.top(); op.pop();
		vals.push (oper (val1, val2, opp));
	}

	return vals.top();
}

int main()
{
	string op; cin >> op;
    cout << res(op);
}