Implement atoi to convert a string to an integer.
说明:实现的atoi函数需要满足以下特征
1、忽略字符串第一个非空格字符前的所有空格(whitespace),第一个非空格字符可以是正负号,后面接纯数字,atoi函数将这些纯数字转换为整型并返回;
3、如果字符串中第一个非空格字符不是一个数字,字符串为空或仅由空格组成,则不对之进行转换;
3、在数字字符后面可以接其他任何字符,但这些非数字的字符将被忽略;
4、如果无法对字符串进行转换,返回0。如果取值过大或过小,返回整型数字的最大值INT_MAX(2147483647)或最小值INT_MIN(-2147483648)。
代码:
int myAtoi(char* str) {
long temp = 0;
int a;
bool sign = true;
while(*str == ' ' || *str == '+' || *str == '-')
{
if(*str == '+' || *str == '-')
{
if(*str == '+' && *(str+1) >= '0' && *(str+1) <= '9')
{
sign = true;
str++;
break;
}
else if(*str == '-' && *(str+1) >= '0' && *(str+1) <= '9')
{
sign = false;
str++;
break;
}
else
return 0;
}
str++;
}
while(*str>= '0' && *str <= '9')
{
a = *str - '0';
temp *= 10;
temp += a;
str++;
if(sign && temp > 2147483647)
return 2147483647;
if(sign == false && temp > 2147483648)
return -2147483648;
}
if(sign)
return (int)temp;
else
return (int)(-temp);
}