Pagini recente » Cod sursa (job #232918) | Cod sursa (job #2009310) | Cod sursa (job #1185142) | Cod sursa (job #2352148)
#include <fstream>
#include <stack>
#include <cstring>
#define BRACKET -1000000001
#define PLUS -1000000002
#define MINUS -1000000003
#define MUL -1000000004
#define DIV -1000000005
using namespace std;
const int NMAX = 100005;
int n;
char s[NMAX];
stack <int> st;
inline bool isDigit(char ch)
{
return '0' <= ch && ch <= '9';
}
int main()
{
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
fin >> (s + 1);
s[0] = '(';
n = strlen(s + 1);
s[n + 1] = ')';
++n;
for (int i = 0;i <= n;++i)
{
if (s[i] == '(')
st.push(BRACKET);
else if (s[i] == ')')
{
int aux = st.top();
st.pop();
while (!st.empty() && st.top() != BRACKET)
{
if (st.top() == PLUS)
{
st.pop();
if (!st.empty())
{
if (st.top() != BRACKET)
{
aux += st.top();
st.pop();
}
else
break;
}
}
if (st.top() == MINUS)
{
st.pop();
if (!st.empty())
{
if (st.top() != BRACKET)
{
aux = st.top() - aux;
st.pop();
}
else
{
aux = 0 - aux;
break;
}
}
}
}
st.pop();
if (!st.empty() && (st.top() == MUL || st.top() == DIV))
{
if (st.top() == MUL)
{
st.pop();
aux = st.top() * aux;
}
else
{
st.pop();
aux = st.top() / aux;
}
st.pop();
}
st.push(aux);
}
else if (isDigit(s[i]))
{
int aux = 0;
while (i <= n && isDigit(s[i]))
{
aux = aux * 10 + (s[i] - '0');
++i;
}
--i;
if (!st.empty() && (st.top() == MUL || st.top() == DIV))
{
if (st.top() == MUL)
{
st.pop();
aux = st.top() * aux;
}
else
{
st.pop();
aux = st.top() / aux;
}
st.pop();
}
st.push(aux);
}
else
{
if (s[i] == '+')
st.push(PLUS);
if (s[i] == '-')
st.push(MINUS);
if (s[i] == '*')
st.push(MUL);
if (s[i] == '/')
st.push(DIV);
}
}
fout << st.top() << "\n";
fin.close();
fout.close();
return 0;
}