Pagini recente » Cod sursa (job #2602730) | Cod sursa (job #3209234) | Cod sursa (job #2602181) | Cod sursa (job #1256794) | Cod sursa (job #2923126)
#include <fstream>
#include <vector>
#include <algorithm>
#include <set>
#include <stack>
#include <cctype>
using namespace std;
int aplic(int a,int b,char c)
{
if(c=='+')return a+b;
if(c=='-')return a-b;
if(c=='/')return a/b;
return a*b;
}
int cod(char ch)
{
if(ch=='/')return 2;
if(ch=='*')return 3;
if(ch=='-' || ch=='+')return 1;
return 0;
}
stack<int>val;
stack<char>op;
void calc()
{
int v2=val.top();
val.pop();
int v1=val.top();
val.pop();
char o=op.top();
op.pop();
val.push(aplic(v1,v2,o));
}
int solve(string s)
{
s='('+s+')';
int n=s.size()-1;
for(int i=0;i<=n;i++)
{
if(s[i]==' ')continue;
if(s[i]=='(')
{
op.push(s[i]);
}
else if(isdigit(s[i]))
{
int x=0;
while(i<=n && isdigit(s[i]))
{
x=x*10+s[i]-'0';
i++;
}
val.push(x);
i--;
}
else if(s[i]==')')
{
while(op.top()!='(')
{
calc();
}
op.pop();
}
else
{
while(cod(s[i])<=cod(op.top()))
{
calc();
}
op.push(s[i]);
}
}
return val.top();
}
main()
{
ifstream cin("evaluare.in");
ofstream cout("evaluare.out");
string s;
getline(cin,s);
cout<<solve(s);
}