Straightforward 8ms C++ solution with short explanation


  • 2
    D

    The main tricky thing here is to use an accumulator type larger than int, and carefully check if the accumulated number passes out of the range of an int. Note the inequality signs in the check. There is one extra valid negative integer, namely, -numeric_limits<int>::max().

    class Solution {
    public:
        int myAtoi(string str) {
            auto first = str.begin(), last = str.end();
            while (isspace(*first) && first != last) { first++; }
            
            int sgn = 1;
            if (*first == '-' || *first == '+') {
                sgn = *first == '-' ? -1 : 1;
                first++;
            }
            
            unsigned long long int result = 0;
            for ( ; isdigit(*first) && first != last; ++first) {
                result = 10 * result + *first - '0';
                if (result >= numeric_limits<int>::max() && sgn == 1) { return numeric_limits<int>::max(); }
                if (result > numeric_limits<int>::max() && sgn == -1) { return numeric_limits<int>::min(); }
            }
            return sgn*result;
        }
    };

Log in to reply
 

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