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);
}