Pagini recente » Cod sursa (job #2427045) | Cod sursa (job #2552379) | Cod sursa (job #504864) | Cod sursa (job #757977) | Cod sursa (job #2969653)
/******************************************************************************
Online C++ Compiler.
Code, Compile, Run and Debug C++ program online.
Write your code in this editor and press "Run" button to compile and execute it.
*******************************************************************************/
#include <fstream>
#include <cstring>
#include <stack>
#include <unordered_map>
using namespace std;
ifstream cin("evaluare.in");
ofstream cout("evaluare.out");
char s[100005];
stack<char> operatori;
stack<int> numere;
unordered_map<char,int> m;
int i,n;
int solve(int x,int y,char o)
{
switch(o)
{
case '+':
return x+y;
case '-':
return y-x;
case '*':
return x*y;
case '/':
return y/x;
}
return -3243;
}
bool cifra(char x)
{
if(x>='0' && x<='9')
return 1;
else
return 0;
}
void prioritati()
{
m['+']=1;
m['-']=1;
m['*']=2;
m['/']=2;
}
int formare()
{
int nou=0;
while(cifra(s[i]) && i<n)
{
nou=nou*10+(s[i]-'0');
i++;
}
i--;
return nou;
}
void nebunie()
{
int x=numere.top();
numere.pop();
int y=numere.top();
numere.pop();
char o=operatori.top();
operatori.pop();
numere.push(solve(x,y,o));
}
int main()
{
prioritati();
cin>>s;
n=strlen(s);
for(i=0;i<n;i++)
{
if(cifra(s[i]))
{
int nou=formare();
numere.push(nou);
}
else
if(s[i]=='(')
operatori.push('(');
else
if(s[i]==')')
{
while(operatori.top()!='(' && !operatori.empty())
nebunie();
if(operatori.empty()==0)
operatori.pop();
}
else
{
while(!operatori.empty() && m[operatori.top()]>=m[s[i]])
nebunie();
operatori.push(s[i]);
}
}
while(!operatori.empty())
nebunie();
cout<<numere.top();
return 0;
}