示例#1
0
Result Calculator::run(Expression expr)
{
    auto rpn = _parser.toRPN(expr);
    RPNStack calcStack;

    while (!rpn.empty()) {
        auto element = rpn.top();
        if (!_parser.isOperator(element)) {
            calcStack.push(element);
            rpn.pop();
            continue;
        }
        auto rhs = BigInteger(calcStack.top());
        calcStack.pop();
        auto lhs = BigInteger(calcStack.top());
        calcStack.pop();

        BigInteger result;

        if (element == "*") {
            result = lhs * rhs;
        } else if (element == "+") {
            result = lhs + rhs;
        } else if (element == "-") {
            result = lhs - rhs;
        }

        calcStack.push(result.value());
        rpn.pop();
    }

    return calcStack.top();
}