C 4ms


  • 0
    D
    int myAtoi(char* s)
    {
         int i=0,sign,max=0;
         long long val=0;
    
         for(i=0;isspace(s[i]);i++)
             ;
    
         sign = (s[i]=='-') ? -1:1;
    
         if(s[i] == '+' || s[i] == '-')
             i++;
    
         for(val=0;isdigit(s[i]);i++)
         {
            val=10*val+(s[i]-'0');
            if(val > INT_MAX)
                  { 
                    max=1;
                    break;
                  }
    
         }
    
        if(max)
        {
            if(sign==1)
                return INT_MAX;
            else
                return INT_MIN;
        }
    
        return val*sign;
    }

  • 0
    K
    This post is deleted!

  • 0
    K

    my code can not work well

    int myAtoi(char* str) {
    	int minus=0;
    	int result=0;
    	int valid=0;
    	
        if(str == NULL)
    		return 0;
    		
    	while(*str<'0' || *str>'9')
    	{
    		
    		if(*str != ' ' && *str != '+' && *str != '-')
        	return 0;
    
        	if(*str == ' ')
        		str++;
        		
        	if(*str == '+' && minus==0)
        	{
        	    str++;
        	}	
        	if(*str == '+' && minus==1)
        	{
        	    str++;
        	    minus=1;
        	}
        	
        	if(*str == '-' && minus==0)
        	{
        		minus=1;
        		str++;
        	}
        	
        	if(*str == '-' && minus==1)
        	{
        		minus=0;
        		str++;
        	}
        	    	
    	}
    
    	valid=1;
    	
    	while(*str>='0' && *str<='9')
    	{
    		result=result*10+*str-'0';
    		str++;
    	}
    	
    	if(minus==1)
    	{
    		result=result*(-1);
    	}
    	
    	return  result; 
    }
    

  • 0
    I

    @kkidou You just need to transform the first legal string. A legal string starts with '+', '-' or ['0','9']. So you should start calculation when you first meet those characters and end with any char which is not a number.


  • 0
    K
    This post is deleted!

Log in to reply
 

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