Easy to understand 5ms C code


  • 9
    Y
    int myAtoi(char* str) {
        char *s = str;
    
        while (*s && isspace(*s)) /* skip spaces */
            s++;
    
        int n = 0;
        if (*s) {
            int sign = 1;
            if (*s == '+')
                s++;
            else if (*s == '-') {
                sign = -1;
                s++;
            }
        
            //while (*s && isspace(*s)) /* skip spaces */
            //    s++;
        
            while (*s && isdigit(*s)) {
                int oldn = n;
                n = n*10 + *s++ - '0';
                if (n/10 != oldn) { /* integer too large or too small */
                    if (sign < 0)
                        return INT_MIN;
                    else 
                        return INT_MAX;
                }
            }
        
            n *= sign;
        }
    
        return n;
    }

  • 0
    K

    Very good and nice code without using long.


  • 0
    S

    Are the below keyword built in some header or library ?

    isdigit
    isspace
    INT_MIN
    INT_MAX

    Is there a other way of finding the integer overflow?


  • 0
    Y

    They reside in <ctype.h> and <limits.h>. I guess there must be other ways to detect overflows, maybe google can help :)


  • 0
    B

    @ssajjan isdigit() and isspace() are built in <ctype.h>, and the other two are built in <limits.h>


  • 0
    L

    @you_dian_tian said in Easy to understand 5ms C code:

    sign

    This is a very readable solution.


Log in to reply
 

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