Skip to content

Instantly share code, notes, and snippets.

@superlayone
Last active August 29, 2015 14:02
Show Gist options
  • Select an option

  • Save superlayone/0b9ddeb5579d9dae27e2 to your computer and use it in GitHub Desktop.

Select an option

Save superlayone/0b9ddeb5579d9dae27e2 to your computer and use it in GitHub Desktop.
atoi v2

##继续来写一个自认为比较完美的atoi版本

直接上代码,关键点在处理溢出的地方!另外优化了判断的逻辑

    int StrToInt(const char* str)
    {
    	int n = 0;
    	int sign = 1;
    	int c;
    	/*
    	static const int INT_MAX = (int)((unsigned)~0 >> 1);
    	static const int INT_MIN = (int)(((unsigned)~0 >> 1) + 1);
    	*/
    	static const int MAX_DIV10 = INT_MAX / 10;
    	static const int MIN_DIV10 = INT_MIN / 10;
    	static const int MAX_MOD10 = INT_MAX % 10;
    	static const int MIN_MOD10 = INT_MIN % 10;
    
    	while(isspace(*str))
    	{
    		++str;
    	}
    	if(*str == '+' || *str == '-')
    	{
    		if(*str == '-')
    		{
    			sign = -1;
    		}
    		++str;
    	}
    	while(isdigit(*str))
    	{
    		c = *str - '0';
    		if(sign > 0 && ( n > MAX_DIV10 || (n == MAX_DIV10 && c > MAX_MOD10)))
    		{
    			n = INT_MAX;
    			break;
    		}
    		else if(sign < 0 && ( -n < MIN_DIV10  || -n == MIN_DIV10  && -c < MIN_MOD10))
    		{
    			n = INT_MIN;
    			break;
    		}
    		n = n * 10 + c;
    		++str;
    	}
    	return sign > 0 ? n : -n;
    }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment