Pagini recente » Cod sursa (job #2793592) | Cod sursa (job #2813345) | Cod sursa (job #452943) | Cod sursa (job #2551746) | Cod sursa (job #2208864)
#include<fstream>
#include<stack>
#include<string>
using namespace std;
bool isoperand(char c)
{
return (c>='0' && c<='9');
}
bool isoperator(char c)
{
return (c== '+' || c== '-' || c== '*' || c=='/');
}
int getpriority(char op)
{
if(op=='+' or op=='-') return 1;
if(op=='*' or op=='/') return 2;
return 0;
}
int higherpriority(char op1, char op2)
{
return (getpriority(op1)>=getpriority(op2));
}
string reversepolishnotation(string exp)
{
stack<char> S;
string postfix;
for(int i = 0;i< exp.size();i++)
{
bool ok=1;
if(isoperator(exp[i]) and ok)
{
ok=0;
while(!S.empty() and S.top()!='(' and higherpriority(S.top(),exp[i]))
{
postfix+= S.top();
S.pop();
}
S.push(exp[i]);
}
if(isoperand(exp[i]) and ok)
{
ok=0;
while(isoperand(exp[i]))
{
postfix +=exp[i];
i++;
}
postfix+=' ';
i--;
}
if (exp[i] == '(' and ok)
{
ok=0;
S.push(exp[i]);
}
if(exp[i] == ')' and ok)
{
ok=0;
while(!S.empty() and S.top()!='(')
{
postfix += S.top();
S.pop();
}
S.pop();
}
}
while(!S.empty())
{
postfix += S.top();
S.pop();
}
return postfix;
}
int val(int op1, int op2, char c)
{
if(c=='+') return op1+op2;
if(c=='-') return op1-op2;
if(c=='*') return op1*op2;
if(c=='/') return op1/op2;
}
int value(string exp)
{
int answer=0;
stack <int> S;
S.push(0);
for(int i=0;i<exp.size();i++)
{
if(isoperand(exp[i]))
{
int nr=0;
while(isoperand(exp[i]))
{
nr=nr*10+exp[i]-'0';
i++;
}
S.push(nr);
i--;
}
if(isoperator(exp[i]))
{
int op1=S.top();
S.pop();
int op2=S.top();
S.pop();
S.push(val(op2,op1,exp[i]));
}
}
return S.top();
}
int main()
{
ifstream f("evaluare.in");
ofstream g("evaluare.out");
string exp;
f>>exp;
string postfix=reversepolishnotation(exp);
g<<value(postfix);
return 0;
}