您的位置:首页 > 其它

[leetcode] Reverse Integer

2014-06-21 09:34 288 查看
Reverse digits of an integer.

Example1: x = 123, return 321

Example2: x = -123, return -321

题目很简单,主要是下面的考虑:

Have you thought about this?

Here are some good questions to ask before coding. Bonus points for you if you have already thought through this!

If the integer's last digit is 0, what should the output be? ie, cases such as 10, 100.

Did you notice that the reversed integer might overflow? Assume the input is a 32-bit integer, then the reverse of 1000000003 overflows. How should you handle such cases?

Throw an exception? Good, but what if throwing an exception is not an option? You would then have to re-design the function (ie, add an extra parameter).

类似的题目有剑指Offer中的第49题,关于边界条件的考虑,包括空指针NULL,空字符串"",正负号,溢出,还有链表操作中删除添加头结点等。

总之在编写代码前,应当对各类边界条件谨慎细心考虑。

以下为atoi的实现:

enum Status{VALID = 0, INVALID};
int g_nStatus = VALID;
long long StrToIntCore(const char *str, bool minus)
{
long long num = 0;
while (*str != '0')
{
if (*str >= '0' && *str <= '9')
{
int flag = minus ? -1 : 1;
// 注意这种乘的方式,符号不是最后再乘,而是每一步都计算一次,用来判断是否溢出
num = num * 10 + flag * (*str - '0');
// 溢出判断
if ((!minus && num > 0x7fffffff) || (minus && num < (signed int)0x80000000))
{
num = 0;
break;
}
++str;
} else
{
num = 0;
break;
}
}
// 为有效转换
if (*str == '\0')
g_nStatus = VALID;
return num;
}
int my_atoi(const char *str)
{
// 判断指针非NULL
assert(str != NULL);
g_nStatus = INVALID;
// 别写成int,防止溢出
long long ret = 0;
// 注意空字符串
if (*str != '\0')
{
bool minus = false;
if (*str == '+')
++str;
else if (*str == '-')
{
minus = true;
++str;
}
if (*str != '\0')
{
ret = StrToIntCore(str, minus);
}
}
return (int)ret;
}


关于atoi的函数可参看:https://github.com/julycoding/The-Art-Of-Programming-By-July/blob/master/ebook/zh/01.03.md
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: