4ms C solution, take me one hour


  • 0
    X
     int myAtoi(char* str) {
     //"NULL"  "000234"  "+23" "-34" "+-34"  "    010"
     if(NULL == str )        
     return 0;    
     int sum  = 0.0;
     int f  = 0;
     int DIV = INT_MAX/10;
     while('\0' != *str)    
     {        
    	if(*str == '+')
    	{
    		str++;
    		if(*str < '0' || *str > '9') return 0;
    		else    f = 0;
    	}
    	if(*str == '-')
    	{
    		str++;
    		if(*str < '0' || *str > '9') return 0;
    		else    f = 1;
    	}
    
    	if(*str >= '0' && *str<= '9' )
    	{
    		if(sum > DIV && f == 0) return INT_MAX;
    		if(sum > DIV && f == 1) return -INT_MAX-1;
    
    		sum = sum * 10.0;
    		
    		if(INT_MAX - *str + '0' < sum  && f == 0) 	    return INT_MAX;
    		if((INT_MAX - (*str - '0') < sum ) && (f == 1)) return -INT_MAX-1;
    
    		sum = sum + *str - '0';
    
    		str++;
    		if(*str == '\0')                    break;
    		else if(*str < '0' || *str > '9')   break;
    	}
    	else
    	{
    	    if(*str >= 'a' && *str <= 'z' )     break;
    		str++;
    	}
    }
    if(f) sum = -sum; 
    return sum;
    }

Log in to reply
 

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