My C++ solution that considers error conditions. Comments embeded. Improvement/Comments welcome.


  • 0
    S
    int evalRPN(vector<string> &tokens) {
        stack<int> s;
        char *c;
    
        if (tokens.size() < 1) return 0;
        for (int num1, num2, pos = 0; pos < tokens.size(); pos++) {
    
            //
            // - If the token is numeric we push it to stack.
            // - If the token is non numeric asume it to be an operator.
            // - In case of operator, the stack must have at least 2 elements.
            // - 1st number poped is the 2nd operand 
            //   and 2nd number poped is the 1st operand.
            // - If operator is anything other than +, -, *, /, then error condition.
            //
    
            // 
            // strtol can hint us about an invalid token when the conversion is 0.
            // If conversion is 0, but scan pointer didn't move then it's non-numeric.
            //
            num2 = strtol(tokens[pos].c_str(), &c, 10);
            if (num2 != 0 || c != tokens[pos].c_str()) s.push(num2);
            else if (s.size() < 2) return 0;
            else {
                num2 = s.top();
                s.pop();
                num1 = s.top();
                s.pop();
                if (tokens[pos] == "+") s.push(num1 + num2);
                else if (tokens[pos] == "-") s.push(num1 - num2);
                else if (tokens[pos] == "*") s.push(num1 * num2);
                else if (tokens[pos] == "/") s.push(num1 / num2);
                else return 0; // Encountered invalid operator
            }
        }
        
        return s.top();
    }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.