Pagini recente » Cod sursa (job #2911281) | Cod sursa (job #1656477) | Cod sursa (job #3002236) | Cod sursa (job #2249234) | Cod sursa (job #3004041)
#include <fstream>
#include <cstring>
#include <stack>
#include <unordered_map>
using namespace std;
ifstream cin("evaluare.in");
ofstream cout("evaluare.out");
char s[100005];
stack<char> operatori;
stack<int> numere;
unordered_map<char, int> m;
int i, n;
int solve(int x, int y, char o)
{
switch (o)
{
case '+':
return x + y;
case '-':
return y - x;
case '*':
return x * y;
case '/':
return y / x;
}
return -3243;
}
bool cifra(char x)
{
if (x >= '0' && x <= '9')
return 1;
else
return 0;
}
void prioritati()
{
m['+'] = 1;
m['-'] = 1;
m['*'] = 2;
m['/'] = 2;
}
int formare()
{
int nou = 0;
while (cifra(s[i]) && i < n)
{
nou = nou * 10 + (s[i] - '0');
i++;
}
i--;
return nou;
}
void nebunie()
{
int x = numere.top();
numere.pop();
int y = numere.top();
numere.pop();
char o = operatori.top();
operatori.pop();
numere.push(solve(x, y, o));
}
int main()
{
prioritati();
cin >> s;
n = strlen(s);
for (i = 0; i < n; i++)
{
if (cifra(s[i]))
{
int nou = formare();
numere.push(nou);
}
else if (s[i] == '(')
operatori.push('(');
else if (s[i] == ')')
{
while (operatori.top() != '(' && !operatori.empty())
nebunie();
if (operatori.empty() == 0)
operatori.pop();
}
else
{
while (!operatori.empty() && m[operatori.top()] >= m[s[i]])
nebunie();
operatori.push(s[i]);
}
}
while (!operatori.empty())
nebunie();
cout << numere.top();
return 0;
}