C++ solution beats 100%


  • 0
    X

    However, the annoying thing is that the requirement is not compatible with the official atoi.

    class Solution {
    public:
        int myAtoi(string str) {
            long long ret = 0;
            string::const_iterator it = str.begin();
            while (it != str.end() && *it == ' ') {
                it++;
            }
            bool is_negative = false;
            if (*it == '+' || *it == '-') {
                is_negative = (*it == '-');
                it++;
            }
            while (it != str.end() && is_valid_digit(*it)) {
                ret *= 10;
                ret += (*it) - '0';
                it++;
                if (!is_negative && ret >= INT_MAX) {
                    return INT_MAX;
                } else if (is_negative && -1*ret <= INT_MIN) {
                    return INT_MIN;
                }
            }
            ret = is_negative ? -1 * ret : ret;
    
            return ret;
        }
    
    private:
        bool is_valid_digit(char c) {
            return c >= '0' && c <= '9';
        }
    };
    

    0_1473129708980_Screen Shot 2016-09-06 at 10.41.34.png


Log in to reply
 

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