听了atoi哥的故事,顺手写个
#define INT_MAX (2147483647)
#define INT_MIN (-2147483648)
int my_atoi(const char * str)
{
if (!str)
return 0;
unsigned int result = 0;
int sign = 1;
if (*str == '-' || *str == '+')
{
if (*str == '-')
{
sign = -1;
}
++str;
}
while(*str >= '0' && *str <= '9')
{
unsigned int digital = *str-'0';
if (result > INT_MAX /10
|| (sign > 0)? (result == INT_MAX/10 && digital > INT_MAX%10)
: (result == (INT_MAX +1)/10 && digital > (INT_MAX+1)%10)
)
{
return sign > 0 ? INT_MAX : INT_MIN;
}
result = result*10 + digital
++str;
}
return ((int)result) * sign;
}