Pagini recente » Cod sursa (job #381310) | Cod sursa (job #2137904) | Cod sursa (job #2409722) | Cod sursa (job #52205) | Cod sursa (job #3212449)
#include <bits/stdc++.h>
using namespace std;
#define pb push_back
#define dbg(x) cout << #x << ": " << x << "\n";
#define sz(x) ((int)x.size())
using ll = long long;
const string fn = "evaluare";
ifstream fin(fn + ".in");
ofstream fout(fn + ".out");
string s;
stack<char> ops;
stack<int> nr;
bool isop(char x)
{
return strchr("+-*/", x);
}
int pri(char x)
{
if (x == '+' || x == '-')
return 1;
if (x == '*' || x == '/')
return 2;
return -1;
}
void comp(char op)
{
int R = nr.top();
nr.pop();
int L = nr.top();
nr.pop();
if (op == '+')
nr.push(L + R);
if (op == '-')
nr.push(L - R);
if (op == '*')
nr.push(L * R);
if (op == '/')
nr.push(L / R);
}
int main()
{
fin >> s;
for (int i = 0; i < sz(s); ++i)
{
if (s[i] == ' ')
continue;
if (s[i] == '(')
ops.push('(');
else if (s[i] == ')')
{
while (ops.top() != '(')
comp(ops.top()), ops.pop();
ops.pop();
}
else if (isop(s[i]))
{
while (!ops.empty() && pri(ops.top()) >= pri(s[i]))
comp(ops.top()), ops.pop();
ops.push(s[i]);
}
else
{
int nrac = 0;
while (isdigit(s[i]))
nrac = nrac * 10 + s[i++] - '0';
nr.push(nrac);
--i;
}
}
while (!ops.empty())
{
comp(ops.top());
ops.pop();
}
fout << nr.top();
return 0;
}