Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321
click to show spoilers.
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?
For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Update (2014-11-10):
Test cases had been added to test the overflow behavior.
//因为没有检测溢出,submit 了好几次才成功
class Solution {
public:
int reverse(int x) {
int ret = 0;
while (x)
{
ret = ret * 10 + x % 10;
if (ret > INT_MAX || ret < INT_MIN) //检测溢出
{
return 0;
}
x /= 10;
}
return ret;
}
};
本文介绍了一个整数反转的算法实现,包括如何处理正负数、最后一位为0的情况及32位整数溢出的问题,并提供了C++代码示例。
280

被折叠的 条评论
为什么被折叠?



