Pagini recente » Cod sursa (job #917663) | Cod sursa (job #514255) | Cod sursa (job #2343780) | Cod sursa (job #1162312) | Cod sursa (job #3165002)
#include <fstream>
#include <string>
#include <deque>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
static inline int eval(deque<char> &D);
static inline int term(deque<char> &D);
static inline int factor(deque<char> &D);
static inline int eval(deque<char> &D)
{
int ans = term(D);
while (!D.empty() && (D.front() == '+' || D.front() == '-'))
{
if (D.front() == '+')
D.pop_front(), ans += term(D);
else
D.pop_front(), ans -= term(D);
}
return ans;
}
static inline int term(deque<char> &D)
{
int ans = factor(D);
while (!D.empty() && (D.front() == '*' || D.front() == '/'))
{
if (D.front() == '*')
D.pop_front(), ans *= factor(D);
else
D.pop_front(), ans /= factor(D);
}
return ans;
}
static inline int factor(deque<char> &D)
{
if (D.empty())
return 1;
if (D.front() == '(')
{
D.pop_front();
int ans = eval(D);
D.pop_front();
return ans;
}
int sign = +1, ans = 0;
if (D.front() == '-')
sign = -1, D.pop_front();
while (!D.empty() && (D.front() >= '0' && D.front() <= '9'))
ans = ans * 10 + (int)(D.front() - '0'), D.pop_front();
return (ans * sign);
}
int main()
{
f.tie(nullptr);
string S = "";
f >> S;
deque<char> D = {};
for (auto &it : S)
D.push_back(it);
g << eval(D) << '\n';
return 0;
}