My C solution (5 ms) clear and with comments


  • 0
    B

    Although it passes the leetcode test, I can't say it has no bugs.

    int myAtoi(char *str) {
        int flag = 1;
        long res = 0;
        
        if (str == NULL) return 0;
        while (*str == ' ' || *str == '\t') ++str;   // eliminate the whitespace before
        if (str == NULL) return 0;                    // return 0 if the string has only whitespace
        if (*str != '-' && *str != '+' && (*str < '0' || *str >'9')) return 0;   // return 0 if the first non-whitespace is not a sign or number.
        if (*str == '-') {flag = -1;++str;}
        else if (*str == '+') {flag = 1; ++str;}
        if (str == NULL) return 0;       // return 0 if the string has only sign
        
        int cnt = 0;   // count the valid number length
        while(*str) {
            if (*str < '0' || *str >'9') break;
            res = res * 10 + *str - 0x30;
            ++str;
            ++cnt;
        }
        
        if (cnt > 10) return flag == 1 ? INT_MAX : INT_MIN;  // return if the length of num is greater then the length of INT_MAX.
        
        res *= flag;
        if (res > INT_MAX) return INT_MAX;
        if (res < INT_MIN) return INT_MIN;
        
    
        return (int)res;
    }

Log in to reply
 

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