clueless coding // TODO: be smarter

LeetCode Evaluate Reverse Polish Notation: CPP Solution



TL;DR Code Solution


int evalRPN(vector<string>& tokens) {

    stack<int> operands;

    for (int i = 0; i < tokens.size(); i++) {

        string item = tokens[i];
        if (item == "+" || item == "-" || item == "/" || item == "*") {
            int op1 = operands.top(); operands.pop();
            int op2 = operands.top(); operands.pop();
            int result;
            if (item == "+")
                    result = op2 + op1;
            if (item == "-")
                    result = op2 - op1;
            if (item == "/")
                    result = op2 / op1;
            if (item == "*")
                    result = op2 * op1;
            operands.push(result);
        }
        else {
            operands.push(stoi(item));
        }
    }

    return operands.top();    

}