[LeetCode]7. Reverse Integer整数反转

时间:2021-06-14 20:45:29

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

Input: 123
Output: 321

Example 2:

Input: -123
Output: -321

Example 3:

Input: 120
Output: 21

Note:
Assume we are dealing with an environment which could only store
integers within the 32-bit signed integer range: [−231, 231 − 1]. For
the purpose of this problem, assume that your function returns 0 when
the reversed integer overflows.

题目要求我们把一个整数翻转过来成为另一个整数,本身很简单,只要利用while循环,不停地对x对10取余和相除,就可以不断地得出每一位的数字。

class Solution {
public int reverse(int x) {
int res = 0,tag=0;
while (x != 0) {
tag = res * 10 + x % 10;
res = tag;
x = x / 10;
}
return res;
}
}

但是这题有个很有意思的地方,题目设置了比较大的输入空间,
X在整形int能显示4个字节[−2^31, 2^31 −
1]这个范围上,已知2^31-1=2147483647,-2^31=-2147483648,假设X=2333333333,反过来就是3333333332,显然大过了int能表示的范围,这里的问题就是怎么判断出反过来的时候溢出了。
这里有一个小方法,在上面的代码中,tag=res*10+x%10,反过来,一定有res=tag/10,
如果t溢出的话,tag/10肯定不可能还是res,我们可以用这个方法来判断溢出。

class Solution {
public int reverse(int x) {
int res = 0,tag=0;
while (x != 0) {
tag = res * 10 + x % 10;
if(tag/10!=res) return 0;
res = tag;
x = x / 10;
}
return res;
}
}

这里的复杂度取决于输入x的长度,所以时间复杂度为log10(x)