Pagini recente » Cod sursa (job #3293483) | Cod sursa (job #3267582) | Cod sursa (job #3283955) | Cod sursa (job #2794451) | Cod sursa (job #3293425)
#include <fstream>
#include <stack>
using namespace std;
ifstream cin("evaluare.in");
ofstream cout("evaluare.out");
int priority(char c)
{
if(c=='+'||c=='-')
return 1;
if(c=='*'||c=='/')
return 2;
return 0;
}
int calc(int n,int m,int c)
{
if(c=='+')
return n+m;
if(c=='-')
return n-m;
if(c=='*')
return n*m;
if(c=='/')
return n/m;
}
int f(string s)
{
int n,m;
stack<int>nr;
stack<char>o;
for(int i=0;i<s.size();i++)
{
if('0'<=s[i]&&s[i]<='9')
{
n=0;
while(i<s.size()&&'0'<=s[i]&&s[i]<='9')
{
n=n*10+s[i]-'0';
i++;
}
i--;
nr.push(n);
continue;
}
if(s[i]=='(')
{
o.push('(');
continue;
}
if(s[i]==')')
{
while(o.top()!='(')
{
m=nr.top();
nr.pop();
n=nr.top();
nr.pop();
nr.push(calc(n,m,o.top()));
o.pop();
}
o.pop();
}
if(s[i]=='+'||s[i]=='-'||s[i]=='*'||s[i]=='/')
{
while(!o.empty()&&priority(s[i])<=priority(o.top()))
{
m=nr.top();
nr.pop();
n=nr.top();
nr.pop();
nr.push(calc(n,m,o.top()));
o.pop();
}
o.push(s[i]);
}
}
while(!o.empty())
{
m=nr.top();
nr.pop();
n=nr.top();
nr.pop();
nr.push(calc(n,m,o.top()));
o.pop();
}
return nr.top();
}
int main()
{
string s;
cin>>s;
cout<<f(s);
return 0;
}