Pagini recente » Cod sursa (job #1144880) | Cod sursa (job #2650085) | Cod sursa (job #2890366) | Registru diplome | Cod sursa (job #2162471)
#include <fstream>
#include <stack>
#include <cstring>
using namespace std;
inline int cti(const char& c)
{
return c-'0';
}
long int pharseVal(int& i, const char* s)
{
int t = 0;
while('0'<= s[i] && s[i] <= '9')
{
t = t*10+cti(s[i]);
i++;
}
i--;
return t;
}
long int applyOp(const long int& a, const long int& b, const char& op)
{
switch(op)
{
case '+':
return a+b;
case '-':
return a-b;
case '*':
return a*b;
case '/':
return a/b;
default:
return 0;
}
return 0;
}
inline bool isOp(const char& c)
{
return (c == '+' || c == '-' || c == '*' || c == '/');
}
inline int grade(const char& op)
{
switch(op)
{
case '+':
return 0;
case '-':
return 0;
case '*':
return 1;
case '/':
return 1;
default:
return 10;
}
return 10;
}
int eval(const char* s)
{
stack<long int> val;
stack<char> op;
int i = 0;
const long int n = strlen(s);
while(i<n)
{
if('0'<= s[i] && s[i] <= '9')
val.push(pharseVal(i,s));
else
if(s[i] == '(')
op.push('(');
else
if(s[i] == ')')
{
while(op.top()!='(')
{
const long int a = val.top();
val.pop();
const long int b = val.top();
val.pop();
val.push(applyOp(b, a, op.top()));
op.pop();
}
op.pop();
}
else
{
while(!op.empty() && isOp(op.top()) && grade(op.top()) >= grade(s[i]))
{
const long int a = val.top();
val.pop();
const long int b = val.top();
val.pop();
val.push(applyOp(b, a, op.top()));
op.pop();
}
op.push(s[i]);
}
i++;
}
while(!op.empty())
{
const long int a = val.top();
val.pop();
const long int b = val.top();
val.pop();
val.push(applyOp(b, a, op.top()));
op.pop();
}
return val.top();
}
char s[100001];
int main()
{
ifstream f("evaluare.in");
ofstream g("evaluare.out");
f.get(s,100000);
g << eval(s);
return 0;
}