Pagini recente » Cod sursa (job #1827250) | Cod sursa (job #3145534) | Cod sursa (job #1927956) | Cod sursa (job #2302081) | Cod sursa (job #3165000)
#include <fstream>
#include <string>
#include <deque>
using namespace std;
ifstream f("evaluare.in");
ofstream g("evaluare.out");
static inline int eval();
static inline int term();
static inline int factor();
deque<char> D;
static inline int eval()
{
int ans = term();
while (!D.empty() && (D.front() == '+' || D.front() == '-'))
{
if (D.front() == '+')
D.pop_front(), ans += term();
else
D.pop_front(), ans -= term();
}
return ans;
}
static inline int term()
{
int ans = factor();
while (!D.empty() && (D.front() == '*' || D.front() == '/'))
{
if (D.front() == '*')
D.pop_front(), ans *= factor();
else
D.pop_front(), ans /= factor();
}
return ans;
}
static inline int factor()
{
if (D.empty())
return 1;
if (D.front() == '(')
{
D.pop_front();
int ans = eval();
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;
for (auto &it : S)
D.push_back(it);
g << eval() << '\n';
return 0;
}