7.Reverse Integer
Description
Reverse digits of an integer.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
Example
Example1: x = 123, return 321
Example2: x = -123, return -321
Analyse
关键在于对溢出数据的判断:
if( (unsigned)x > INT_MAX) 溢出
实际上,x的正负对是否溢出没有影响,所以可以直接比较数值的大小。
class Solution {
public:
int reverse(int x) {
int x_ = 0;
while (x != 0)
{
if (abs(x_) > INT_MAX / 10)
return 0;
x_ = x_ * 10 + x % 10;
x = x / 10;
}
return x_;
}
};
复杂度分析
时间复杂度:O(n)
空间复杂度:O(1)
本文介绍了一种有效的整数反转算法,特别关注了32位有符号整数的处理,并提供了详细的C++实现代码及溢出判断逻辑。通过迭代方式完成数字的反转,同时确保在反转过程中不会发生溢出。
4万+

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



