Pagini recente » Cod sursa (job #235790) | Cod sursa (job #1682430) | Cod sursa (job #849077) | Cod sursa (job #2590951) | Cod sursa (job #2703527)
#include <fstream>
#include <cstring>
#include <cctype>
#include <stack>
using namespace std;
typedef long long ll;
const int NMAX=50;
ifstream cin("evaluare.in");
ofstream cout("evaluare.out");
stack<ll> polo;
stack<char> op;
char ch[NMAX+4];
short get(char x)
{
switch(x)
{
case '+':
case '-': return 1;
case '/':
case '*': return 2;
}
return 0;
}
int main()
{
ios_base::sync_with_stdio(false);
cin.tie(NULL);
ll n,x,i,aux,tp;
char ca;
bool ok;
cin>>ch;
n=strlen(ch);
x=0;
ok=1;
for(i=0;i<n;i++)
{
if(ch[i]=='('){
op.push(ch[i]);
continue;
}
if(isdigit(ch[i])){
x=x*10+(ch[i]-'0');
continue;
}
if(ok)
polo.push(x);
else
ok=1;
x=0;
if(ch[i]==')'){
while(op.top()!='('){
tp=polo.top();
polo.pop();
aux=polo.top();
polo.pop();
if(op.top()=='+'){
op.pop();
polo.push(aux+tp);
}
else
if(op.top()=='-'){
op.pop();
polo.push(aux-tp);
}
else{
op.pop();
polo.push(aux*tp);
}
}
op.pop();
ok=0;
continue;
}
if(op.empty() or op.top()=='(' or get(op.top())<get(ch[i])){
op.push(ch[i]);
continue;
}
while(!op.empty() and op.top()!=')' and get(ch[i])<=get(op.top())){
tp=polo.top();
polo.pop();
aux=polo.top();
polo.pop();
if(op.top()=='+'){
op.pop();
polo.push(aux+tp);
}
else
if(op.top()=='-'){
op.pop();
polo.push(aux-tp);
}
else
if(op.top()=='*'){
op.pop();
polo.push(aux*tp);
}
else{
op.pop();
polo.push(aux/tp);
}
}
op.push(ch[i]);
}
if(ch[n-1]!=')')
polo.push(x);
while(!op.empty()){
tp=polo.top();
polo.pop();
aux=polo.top();
polo.pop();
ca=op.top();
if(ca=='+'){
op.pop();
polo.push(aux+tp);
}
else
if(ca=='-'){
op.pop();
polo.push(aux-tp);
}
else
if(op.top()=='*'){
op.pop();
polo.push(aux*tp);
}
else{
op.pop();
polo.push(aux/tp);
}
}
cout<<polo.top();
return 0;
}