您的位置:首页 > 其它

[leetcode 8] String to Integer (atoi)

2014-11-08 11:34 211 查看
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.

[Solution]

注意点:

1)前缀空格

2)正负号

3)溢出 (可以使用long long int防止溢出)

int atoi(const char *str)
{
long long int number = 0;
int flag = 1;
while ((str != NULL) && (*str == ' '))
str++;
if (*str == '+')
{
flag = 1;
str++;
}
else if (*str == '-')
{
flag = -1;
str++;
}

while ((*str != '\0') && (*str >= '0' && *str <= '9'))
{
number = number * 10 + (*str - '0') * flag;
if ((number < INT_MIN) ||  number > INT_MAX)
return (flag > 0 ? INT_MAX : INT_MIN);
str++;
}

return number;
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: