您的位置:首页 > 其它

算法分析与设计week05--7.Reverse Integer

2017-10-19 10:38 253 查看

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)

参考链接:http://www.cnblogs.com/grandyang/p/4125588.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: