Pagini recente » Cod sursa (job #864224) | Cod sursa (job #949322) | Cod sursa (job #66951) | Cod sursa (job #1632276) | Cod sursa (job #1199200)
#include <iostream>
#include <cstdio>
#include <stack>
#include <unordered_map>
#include <cctype>
using namespace std;
int apply(char op, int x, int y)
{
switch (op) {
case '+': return x+y;
case '-': return x-y;
case '*': return x*y;
case '/': return x/y;
default: return 0;
}
}
void reduce(stack<char>& ops, stack<int>& nums)
{
char op = ops.top();
ops.pop();
int num = nums.top();
nums.pop();
nums.top() = apply(op, nums.top(), num);
}
int main()
{
ios::sync_with_stdio(false);
freopen("evaluare.in", "r", stdin);
freopen("evaluare.out", "w", stdout);
unordered_map<char, int> precedence = {{'(', 0}, {'+', 1}, {'-', 1}, {'*', 2}, {'/', 2}};
string expr;
getline(cin, expr);
expr = '('+expr+')';
stack<char> ops;
stack<int> nums;
for (auto it = expr.begin(); it != expr.end(); ) {
if (isdigit(*it)) {
int num = 0;
do {
num = num*10+*it-'0';
++it;
} while (isdigit(*it));
nums.push(num);
}
else {
if (*it == '(') {
ops.push(*it);
}
else if (*it == ')') {
while (ops.top() != '(') {
reduce(ops, nums);
}
ops.pop();
}
else {
while (precedence[ops.top()] >= precedence[*it]) {
reduce(ops, nums);
}
ops.push(*it);
}
++it;
}
}
printf("%d\n", nums.top());
return 0;
}