题目:
8. String to Integer (atoi)
问题描述:
讲一个字符串转为数字
“+123”->123
"-123"->-123
" -123"->-123
" a1"->0
"1 23"->1
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.
Requirements for atoi:
The function first discards as many whitespace characters as necessary until the first non-whitespace character is found. Then, starting from this character, takes an optional initial plus or minus sign followed by as many numerical digits as possible, and interprets them as a numerical value.
The string can contain additional characters after those that form the integral number, which are ignored and have no effect on the behavior of this function.
If the first sequence of non-whitespace characters in str is not a valid integral number, or if no such sequence exists because either str is empty or it contains only whitespace characters, no conversion is performed.
If no valid conversion could be performed, a zero value is returned. If the correct value is out of the range of representable values, INT_MAX (2147483647) or INT_MIN (-2147483648) is returned.
int myAtoi(char* str) {
int len=strlen(str);
long r=0;
bool alpha=false;//判断字符串中是否已经出现了字符
bool flag=true;//判断字符串中的正负,初始为正值
bool negative=false;
bool midspace=false;//判断字符串中间是否有空格,那么一旦有数字开始,就将midspace标记为true
int i;
for(i=0;i<len;i++)
{
if(str[i]>'9'||str[i]<'0')
{
if(str[i]=='+'||str[i]=='-')
{
if(alpha==true)
return 0;
alpha=true;
if(str[i]=='-')
negative=true;
}
else if(str[i]==' ')
{
if(alpha==true)
break;
if(midspace==true)
break;
continue;
}
else
break;
}
else
{
midspace=true;
r=r*10+str[i]-'0';
if(r>INT_MAX && !negative)
return INT_MAX;
if(r>INT_MAX && negative)
return INT_MIN;
}
}
if(negative==true)
return -r;
else
return r;
}