Share my 4ms C solution


  • 0
    D
    int myAtoi(char* str) {
    int res = 0;
    int flag = 1;
    while (*str == ' ' || *str == '\t' || *str == '\n')str++;
    if (*str == '-') {
    	flag = -1;
    	str++;
    }
    else if (*str == '+') {
    	str++;
    }
    while (*str == '0')str++;
    while (*str >= '0'&&*str <= '9') {
    	if (res > INT_MAX / 10 || res * 10 > INT_MAX - (*str - '0')) {
    		if (flag==1) return INT_MAX;
    		else return INT_MIN;
    	}
    	res = res * 10 + (*str - '0');
    	str++;
     }
    return flag*res;
    }
    

    res > INT_MAX / 10 || res * 10 > INT_MAX - (*str - '0') is important.


Log in to reply
 

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