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,str是否为空;
2,str头一个数是否为结束符;
3,str是否包含空格,如有,跳过;
4,str是否包含数字正负信息;
5,str中字符是否为0-9之间的字符;
6,在while循环中result是否越界(此处没写,直接写在最后,应该是写在循环里);
7,注意效率;
11/17/2013更新:还需考虑下如果+-号之后为空的情况,处理方法应该以设定一个静态全局然后直接改变其值为佳。代码未更新。
class Solution {
public:
int atoi(const char *str) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if(str == NULL || *str == '\0')
//throw exception("invalid");
return 0;
bool ifNeg = false;
long long result = 0; //?
while(*str == ' ')
str++;
if(*str == '-')//if it is negtive number
{
ifNeg = true;
str++;
}
else if(*str == '+')//if it is positive number
{
str++;
}
while(str != '\0')
{
if( ( ( *str - '0') >= 0) && ( (*str - '0') <= 9 ) )
{
int digit = *str - '0';
result = result *10 + digit;
str++;
}
else //if it is not a digit
break;
}
int po = 1;
if(ifNeg)
po = -1;
if(result*po > INT_MAX)
return INT_MAX;
else if(result*po < INT_MIN)
return INT_MIN;
else
return result*po;
}
};