Pagini recente » Cod sursa (job #3005351) | Cod sursa (job #2747733) | Cod sursa (job #111232) | Cod sursa (job #2001682) | Cod sursa (job #2171384)
#include <bits/stdc++.h>
using namespace std;
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
char s[100005];
int lg;
stack <int> val;
stack <char> op;
void read()
{
fin>>s;
lg=strlen(s);
fin.close();
}
int findnr(int &poz)
{
int nou=0;
while(isdigit(s[poz])==1)
{
nou=nou*10+s[poz]-'0';
poz++;
}
poz--;
return nou;
}
int Operator(char c)
{
if(strchr("+-*/",c)) return 1;
return 0;
}
int Prioritate(char c)
{
if(c=='(') return 0;
if(c=='+' || c=='-') return 1;
if(c=='*' || c=='/') return 2;
}
void solve()
{
int i;
int nr,a,b,operatie,r,pr;
for(i=0;i<lg;++i)
{
if(isdigit(s[i]))
{
nr=findnr(i);
val.push(nr);
}
if(s[i]=='(') op.push(s[i]);
if(s[i]==')')
{
while(op.top()!='(')
{
b=val.top(); val.pop();
a=val.top(); val.pop();
operatie=op.top(); op.pop();
if(operatie=='+') r=a+b;
if(operatie=='*') r=a*b;
if(operatie=='/') r=a/b;
if(operatie=='-') r=a-b;
val.push(r);
}
op.pop();
}
if(Operator(s[i])==1)
{
pr=Prioritate(s[i]);
while(op.size()>0 && Prioritate(op.top())>=pr)
{
b=val.top(); val.pop();
a=val.top(); val.pop();
operatie=op.top(); op.pop();
if(operatie=='+') r=a+b;
if(operatie=='*') r=a*b;
if(operatie=='/') r=a/b;
if(operatie=='-') r=a-b;
val.push(r);
}
op.push(s[i]);
}
}
while(op.size()>0)
{
b=val.top(); val.pop();
a=val.top(); val.pop();
operatie=op.top(); op.pop();
if(operatie=='+') r=a+b;
if(operatie=='*') r=a*b;
if(operatie=='/') r=a/b;
if(operatie=='-') r=a-b;
val.push(r);
}
fout<<val.top();
}
int main()
{
read();
solve();
return 0;
}