Accepted C++ 8 ms (String to Integer (atoi)) !


  • 2
    F

    Although it is very rigid, but just 8 ms:

    int myAtoi(string str) {
        if(((str[0]-'0'<0)||(str[0]-'9'>0))&&(str[0]!='+')&&(str[0]!='-')&&(str[0]!=' '))
        {
            return 0;
        }
        int flag=1,index=0;
        double answer=0;
        while(str[index]==' ')
        {
            index++;
        }
        if(str[index]=='+')
        {
            flag=1;
            index++;
        }
        else if(str[index]=='-')
        {
            flag=-1;
            index++;
        }
        for(int i=index,s=str.length();i<s;i++)
        {
            if((str[i]>='0')&&(str[i]<='9'))
            {
                answer=(str[i]-'0')+answer*10;
            }
            else
            {
                break;
            }
        }
        answer=answer*flag;
        if(answer>2147483647)
        {
            return 2147483647;
        }
        else if(answer<-2147483648)
        {
            return -2147483648;
        }
        else
        {
            return answer;
        }
    }
    

    To find ways to improve!


  • 0
    Z

    hi, With reference to your code,this is mine。
    add two lines。

        double max = (double)2147483647;
    	double min = -2147483648;
    	
    	if (((str[0] - '0'<0) || (str[0] - '9'>0)) && (str[0] != '+') && (str[0] != '-') && (str[0] != ' '))
    		return 0;
    
    	int index = 0;
    	while(str[index] == ' ')
    		index++;
        
        if ((str[index] == '-' || str[index] == '+') && (str[index + 1] == '-' || str[index + 1] == '+'))
    		return 0;
    
    	int flag=1;
    
    	if (str[index] == '-')
    	{
    		flag = -1;
    		index++;
    	}
    	else if (str[index] == '+')
    	{
    		flag = 1;
    		index++;
    	}
    
    	double res = 0;
    
    	for (int i = index; i < str.size() ; i++)
    	{
    		if (str[i] - '0' >= 0 && str[i] - '9' <= 0)
    			res = str[i] - '0' + res * 10;
    		else
    			break;
    	}
    
    	res = res*flag;
    
    	if (res > max)
    		return max;
    	else if (res < min)
    		return min;
    	else
    		return res;
    

    but, in my visual studio 2015, it give this error.Compiler Warning (level 2) C4146,:https://msdn.microsoft.com/query/dev14.query?appId=Dev14IDEF1&l=ZH-CN&k=k(C4146)&rd=true.


  • 0
    Z

    using double to store the int is a good way to judge whether overflow.


  • 0
    Z

    using double to store the int is a good way to judge whether overflow.


Log in to reply
 

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