Pagini recente » Cod sursa (job #50891) | Cod sursa (job #1903790) | Cod sursa (job #732731) | Cod sursa (job #827433) | Cod sursa (job #2756718)
#include <fstream>
#include <string>
#include <stack>
#include <cassert>
using namespace std;
class ExprEvaluator{
public:
int Evaluate(string expr)
{
for (int i = 0; i < expr.size(); ++i) {
if (isDigit(expr[i])) {
int value = expr[i] - '0';
while (i + 1 < expr.size() && isDigit(expr[i + 1])) {
value = value * 10 + expr[++i] - '0';
}
numbers_.emplace(value);
continue;
}
if (expr[i] != '(')
Pop(priority(expr[i]));
if (expr[i] != ')') {
operators_.emplace(expr[i]);
priorities_.emplace(priority(expr[i]));
}
}
int result = numbers_.top();
numbers_.pop();
return result;
}
private:
bool isDigit(char c) {
return '0' <= c && c <= '9';
}
int priority(char c) {
if (c == '(' || c == ')') return -1;
if (c == '+' || c == '-') return 1;
if (c == '*' || c == '/') return 2;
return 3;
}
void Pop(int operatorPriority) {
while (!priorities_.empty() && priorities_.top() >= operatorPriority) {
char op = operators_.top();
operators_.pop();
priorities_.pop();
if (op == '(')
return;
int b = numbers_.top(); numbers_.pop();
int a = numbers_.top(); numbers_.pop();
if (op == '+') numbers_.emplace(a + b);
if (op == '-') numbers_.emplace(a - b);
if (op == '*') numbers_.emplace(a * b);
if (op == '/') numbers_.emplace(a / b);
}
}
stack<int> numbers_;
stack<int> operators_;
stack<int> priorities_;
};
int main()
{
ifstream fin("evaluare.in");
ofstream fout("evaluare.out");
ExprEvaluator exprEvaluator;
string s;
fin >> s;
fout << exprEvaluator.Evaluate('(' + s + ')');
return 0;
}