String to Integer (atoi)
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.
实现 atoi 将字符串转化成整数。
暗示:考虑所有可能的输入情况。
说明:我们故意使问题模糊,你应该集合上面要求的所有可能的输入。
分析:
需要考虑所有的输入情况,忽略字符串首尾的空格,字符串首非空字符+-为合法字符,其他非数字字符为非法字符,字符串中数字字符后第一次遇见非数字字符时停止转换,考虑整数的溢出。
int myAtoi(char* str) {
int minusflag = 0;
long long int number = 0;/*避免整型溢出*/
char *pstr = str;
char *pdigStart = str, *pdigEnd = NULL;
if(NULL == str || NULL == *str)/*空指针*/
return 0;
/*开头为空格,找出非空格开头*/
if(*str == ' ' || *str == '\t')
{
while(*pstr && (*pstr == ' ' || *pstr == '\t'))
{
++pstr;
}
if(!*pstr)/*字符串全是空格*/
{
return 0;
}
else
{
pdigStart = pstr; /*第一个非空格字符*/
}
}
/*为负数,标志置1*/
if(*pdigStart == '-')
{
minusflag = 1;
++pdigStart;
}
else if(*pdigStart == '+')
{
++pdigStart;
}
/*找到合法字符0-9*/
for(pstr = pdigStart; *pstr && (*pstr >= '0' && *pstr <= '9'); ++pstr);
pdigEnd = pstr - 1;
/*字符转数字*/
for(pstr = pdigStart; pstr <= pdigEnd; ++pstr)
{
number = 10*number + (*pstr - '0');
if(number > 0x7fffffff) /*溢出*/
{
if(minusflag == 0)/*正数,返回上界*/
{
return (int)2147483647;
}
else /*负数下界*/
{
return (int)(-2147483648);
}
}
}
if(minusflag) /*为负数*/
{
number *= -1;
}
return number;
}