Share my 6ms C solution


  • 1
    M
    
    #include "stdio.h"
    #define INT_MIN (-2147483648)
    #define INT_MAX 2147483647
    int tens[] = { 1,10,100,1000,10000,100000,1000000,10000000,100000000,1000000000 };
    
    int str_len(char *str)
    {
    	int len = 0;
    	while (*str != '\0' && (*str >= '0' && *str <= '9'))
    	{
    		len++;
    		str++;
    	}
    	return len;
    }
    
    
    int myAtoi(char* str) {
    	long long number = 0;
    	int sign = 1;
    	if (*str == '\0')
    		return number;
    	while (*str == ' ')
    		str++;
    	while (*str == '0')
    		str++;
    	if (*str == '-' || *str == '+')
    	{
    		if(*str == '-')
    			sign = -1;
    		str++;
    	}
    	if (!(*str >= '0' && *str <= '9'))
    	{
    		return 0;
    	}
    	while (*str == '0')
    		str++;
    	int i = 0;
    	int len = str_len(str);
    	if (len > 10)
    	{
    		if (sign>0)
    			return INT_MAX;
    		else
    			return INT_MIN;
    	}
    	while (*str != '\0' || (i<len))
    	{
    		number += (*str - '0')*tens[len - 1 - i];
    		str++;
    		i++;
    	}
    	number *= sign;
    	if (number > INT_MAX)
    		return INT_MAX;
    	if (number < INT_MIN)
    		return INT_MIN;
    	else
    		return (int)number;
    }
    
    int main()
    {
    	char str[] = "      -11919730356x";
    	printf("%d\n",myAtoi(str));
        return 0;
    }
    
    

Log in to reply
 

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