题目描述:
解析:
这个题不难,需要注意的是反转后是否超出32位有符号整数范围。
我的解决办法就是使用double,用double来接收,最后来判断
class Solution {
public int reverse(int x) {
int temp = x;
double y = 0;
int count = 0;
while(temp != 0) {
count++;
temp /= 10;
}
for(int i = 0; i < count; i++) {
y = x % 10 + y * 10;
if(y > Math.pow(2,31)-1 || y < Math.pow(-2,31)) {
return 0;
}
x /= 10;
}
return (int)y;
}
}
第二种方法就是 res每次更新后除10,然后跟上一次的res比较一下,如果不相等,就是溢出
class Solution {
public int reverse(int x) {
int res = 0;
int last = 0;
while(x!=0) {
//每次取末尾数字
int tmp = x%10;
last = res;
res = res*10 + tmp;
//判断整数溢出
if(last != res/10)
{
return 0;
}
x /= 10;
}
return res;
}
}
- 时间复杂度:O(log|x|)
- 空间复杂度:O(1)