Share my 4ms C solution. Short.


  • 1
    A
    int myAtoi(char* str) {
        int n=0; bool negtive=false;
        int tenth=INT_MAX/10;
    
        while (*str==' ') str++;
        if (*str=='+') str++;
        else if (*str=='-') {negtive=true; str++;}
    
        while (*str) {
            if (*str<'0' || *str>'9') break;
            if (n<=tenth) {
                n=n*10+(int)(*str-'0');
                if (n>=0) {str++; continue;}//continue if not oveflowed
            }
            //if overflowed
            if (negtive) return INT_MIN;
            return INT_MAX;
        }
    
        if (negtive) n=-n;
        return n;
    }

Log in to reply
 

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