I can deal with it by one 'while'


  • 0
    J

    I think I can deal with it by only one 'while'

    int myAtoi(char* str) {
        int bits = 0;
        int sign = 1;
        char *p = str;
        long result = 0;
        bool first = true;
        // string with nothing!
        if (*p == '\0') return 0;
        
        while (*p != '\0')
        {
            // the fist whitespaces
            if (first && *p == ' ')
            {
                ++p;
                continue;
            }
            
            if (first && (*p == '-'|| *p == '+'))
            {
                if (*p == '-')
                {
                   sign = -1;
                }
                first = false;
                ++p;
                continue;
            }
            
            // keep from overflow
            if (bits > 10) return sign>0?INT_MAX:INT_MIN;
            
            if (*p > '9' || *p < '0')
                break;
            
            result = result*10 + (*p -'0');
            first = false;
            ++p;
            ++bits;
        }
        result *= sign;
        result = result < INT_MIN?INT_MIN:\
        result > INT_MAX?INT_MAX:result;
        return result;
    }
    

Log in to reply
 

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