#include #include #include #include RPN::RPN() {} RPN::RPN(const RPN& other) { (void)other; } enum Operator { PLUS, MINUS, MULTIPLY, DIVIDE }; static bool isOperator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; } static Operator getOperator(char c) { switch (c) { case '+': return PLUS; case '-': return MINUS; case '*': return MULTIPLY; case '/': return DIVIDE; default: throw std::runtime_error(""); } } static long operate(const Operator& op, const long& a, const long& b) { switch (op) { case PLUS: return a + b; case MINUS: return a - b; case MULTIPLY: return a * b; case DIVIDE: return a / b; } } long RPN::evaluate(const std::string& expression) const { std::stack stack; for (size_t i = 0; i < expression.size(); ++i) { if (expression[i] == ' ') continue; if (isOperator(expression[i])) { if (stack.size() < 2) throw std::runtime_error(""); const Operator op = getOperator(expression[i]); const long b = stack.top(); stack.pop(); const long a = stack.top(); stack.pop(); if (op == DIVIDE && b == 0) throw std::runtime_error(""); stack.push(operate(op, a, b)); } else if (std::isdigit(static_cast(expression[i]))) { stack.push(expression[i] - '0'); } else { throw std::runtime_error(""); } } if (stack.size() != 1) throw std::runtime_error(""); return stack.top(); } RPN& RPN::operator=(const RPN& other) { if (this == &other) return *this; return *this; } RPN::~RPN() {}