Pagini recente » Cod sursa (job #2274344) | Cod sursa (job #2512881) | Cod sursa (job #858993) | Cod sursa (job #1034276) | Cod sursa (job #1876684)
#include <iostream>
#include <stack>
#include <cstdio>
#include <cstring>
#include <cctype>
using namespace std;
int Convert(char s[], int &i)
{
int n = strlen(s);
int ans = 0;
for(i; i < n; ++i)
{
if(isdigit(s[i]))
ans *= 10, ans += s[i] - '0';
else break;
}
return ans;
}
int Operation(int x, int y, char c)
{
switch (c)
{
case '+' : return x + y;
case '-' : return y - x;
case '*' : return x * y;
case '/' : return y / x;
};
}
bool Verif(char a, char b) /// return 1 daca trebuie scos din stiva elem din op.top()
{
switch (a)
{
case '+' : {
return 1;
}
case '-' : {
return 1;
}
case '*' : {
switch (b)
{
case '/' : return 1;
default : return 0;
};
}
case '/' : {
switch (b)
{
case '*' : return 1;
default : return 0;
};
}
};
}
stack <char> op;
stack <int> pol;
char s[100005];
int main()
{
freopen("evaluare.in","r",stdin);
freopen("evaluare.out","w",stdout);
gets(s);
int n = strlen(s);
for(int i = 0; i < n; ++i)
{
if(isdigit(s[i]))
{
pol.push(Convert(s, i));
i--;
}
else
{
if(op.empty() || op.top() == '('){
op.push(s[i]);
continue;
}
if(s[i] == ')'){
while(!op.empty() && op.top() != '('){
int x = pol.top();
pol.pop();
int y = pol.top();
pol.pop();
char c = op.top();
op.pop();
pol.push(Operation(x, y, c));
}
op.pop();
continue;
}
while(!op.empty() && Verif(s[i], op.top()))
{
char c = op.top();
op.pop();
int x = pol.top();
pol.pop();
int y = pol.top();
pol.pop();
pol.push(Operation(x, y, c));
}
op.push(s[i]);
}
}
while(!op.empty())
{
int x = pol.top();
pol.pop();
int y = pol.top();
pol.pop();
char c = op.top();
op.pop();
pol.push(Operation(x, y, c));
}
cout << pol.top();
return 0;
}