Implement atoi to convert a string to an integer.
Hint: Carefully consider all possible input cases. If you want a challenge, please do not see below and ask yourself what are the possible input cases.
Notes: It is intended for this problem to be specified vaguely (ie, no given input specs). You are responsible to gather all the input requirements up front.
//1:字符为‘ ’, 2: 字符为+, -,3: 数组超出int范围 4: 数字字符中混合了其它字符 ; 5: 结果的正负号
int atoi(const char *str)
{
if(str == NULL || *str == '\0')
return 0;
while(*str != '\0' && *str == ' ')
{
str++;
}
bool flag = false;
if(*str == '-')
{
flag = true;
str++;
}
else if(*str == '+')
{
str++;
}
if(*str == '\0' || *str > '9' || *str < '0')
return 0;
long long result = 0;
while(*str != '\0')
{
if(*str >= '0' && *str <= '9')
{
result = 10 * result + *str - '0';
if(flag == false && result >= INT_MAX)
{
return INT_MAX;
}
if(flag == true && (-result) <= INT_MIN)
{
return INT_MIN;
}
}
else
break;
str++;
}
if(flag)
result = -result;
return (int)result;
}