Pagini recente » Cod sursa (job #187784) | Cod sursa (job #1154126) | Cod sursa (job #1754340) | Cod sursa (job #1640653) | Cod sursa (job #2302940)
#include <cstdio>
#include <stack>
#include <cstring>
using namespace std;
stack <int>numere;
stack <char>operatii;
char s[100005];
int prioritate(char s1)
{
if(operatii.empty())
return 1;
if(operatii.top()=='(')
return 1;
if(s1=='*' && operatii.top()=='+'||s1=='*' && operatii.top()=='-'||s1=='/' && operatii.top()=='+'||s1=='/' && operatii.top()=='-')
return 1;
return 0;
}
int calculam(char s1)
{
int x=numere.top();
numere.pop();
int y=numere.top();
numere.pop();
if(s1=='+')
{
numere.push(x+y);
return x+y;
}
if(s1=='-')
{
numere.push(y-x);
return y-x;
}
if(s1=='*')
{
numere.push(x*y);
return x*y;
}
if(s1=='/')
{
numere.push(y/x);
return y/x;
}
}
int main()
{
freopen("evaluare.in","r",stdin);
freopen("evaluare.out","w",stdout);
scanf("%s",s);
int n=strlen(s);
for(int i=0; i<n; i++)
{
if(operatii.empty() && (s[i]<='0'||s[i]>='9'))
{
operatii.push(s[i]);
// continue;
}
else if(s[i]<='9' && s[i]>='0')
{
int x=0;
while(s[i]<='9' && s[i]>='0')
{
x=x*10+(s[i]-'0');
i++;
}
i--;
numere.push(x);
//continue;
}
else if(prioritate(s[i])==1)
{
operatii.push(s[i]);
// continue;
}
else if(s[i]=='(')
{
operatii.push(s[i]);
//continue;
}
else if(s[i]==')')
{
while(operatii.top()!='(')
{
char y=operatii.top();
calculam(y);
operatii.pop();
}
operatii.pop();
//continue;
}
else{while(prioritate(s[i])==0)
{
calculam(operatii.top());
operatii.pop();
}
operatii.push(s[i]);}
}
while(!operatii.empty())
{
char c=operatii.top();
calculam(c);
operatii.pop();
}
int y=numere.top();
printf("%d",numere.top());
return 0;
}