您的位置:首页 > 其它

LeetCode 8. String to Integer (atoi)

2017-01-20 10:57 405 查看
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.

分析:

考虑各种边界情况。

” 000123” return 123

” +000123” return 123

“-123” return -123

“123a4x” return 123

越界情况:

“2147483647” return 2147483647

“-2147483648” return -2147483648

“2147483648” return 2147483647

“-2147483649” return 2147483647

越界情况可以比较中间结果是否已经达到2147483640,即INT_MAX/10。然后再判断下一位值的情况,进而判断是否越界。

class Solution {
public:
int myAtoi(string str)
{
int result = 0;
int i = 0;
int sign = 1;

if (str[i] != '\0')
{
while (str[i] == ' ') ++i;
if (str[i] == '+') ++i;
else if (str[i] =='-') sign = -1, ++i;

while (str[i] == '0') ++i;

if (str[i] != '0')
{
while (str[i] != '\0')
{
if (str[i] >= '0' && str[i] <= '9')
{
if (result > INT_MAX / 10) return sign == -1 ? INT_MIN : INT_MAX;  // 越界情况
if (result == INT_MAX / 10) {
if ((str[i] - '0' <= 7 && sign == 1) || (str[i] - '0' <= 8 && sign == -1))
{
result = (result * 10) + (str[i++] - '0');
return sign * result;
}
return sign == -1 ? INT_MIN : INT_MAX;  // 越界情况
}
result = (result * 10) + (str[i++] - '0');
}
else {
break;
}
}
}
}
return sign * result;
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息