您的位置:首页 > 编程语言 > Java开发

#leetcode# Reverse Integer

2014-12-26 16:10 281 查看
https://oj.leetcode.com/problems/reverse-integer/

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: x = -123, return -321
--------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
这题是个简单题没错, 理论上讲知道用mod来取各位上的数字就会反转Integer,之前也一直以为自己做的是正确的, 但是leetcode 于11/10/2014 更新了check integer overflow的test case, 于是再来做这题。。 发现了很多问题

以前的代码是这样的:

public class Solution {
public int reverse(int x) {
if(Math.abs(x) < 10){
return x;
}

boolean isNeg = false;
if(x < 0){
isNeg = true;
x = Math.abs(x);
}

int result = 0;
while(x > 0){
int tmp = x % 10;
x = x / 10;
result = tmp + 10 * result;
}
// 如果溢出, 返回指定值
if(result < 0){
return -1;
}
if(isNeg){
return -result;
}
return result;
}
}
上面的代码中我还自以为是的对溢出做了处理, 实际上现在再来run这个代码的话会被这个test case卡住:
Input:	1534236469
Output:	1056389759
Expected:	0

原因很明显了, 溢出的太多, 导致溢出后的数字仍然是正的。

反省了上面的错误, 尝试代码如下:

public class Solution {
public int reverse(int x) {
if(Math.abs(x) < 10){
return x;
}
int result = 0;
int tmp = 0;
while(Math.abs(x) > 0){
if(Math.abs(result) > Integer.MAX_VALUE / 10){
return 0;
}
tmp = x % 10;
x = x / 10;
result = result * 10 + tmp;
}

return result;
}
}


这段代码看起来貌似没什么问题了, 实际情况是:

Input:	-2147483648
Output:	-2147483648
Expected:	0


我以为是对于溢出的判断有问题, 尝试了多种方法, 均没有改善, 又回头认真的学习Java Integer..

Integer.MAX_VALUE : 2147483647

Integer.MIN_VALUE:     -2147483648

那么 Integer.MIN_VALUE 的绝对值的理论值是 2147483648, 但是它溢出了。。。所以 Math.abs(Integer.MIN_VALUE)的值还是 -2147483648

被自以为是的一段偷懒代码给坑了

正确的代码:

public class Solution {
public int reverse(int x) {

int result = 0;
int tmp = 0;
while(Math.abs(x) > 0){
if(Math.abs(result) > Integer.MAX_VALUE / 10){
return 0;
}
tmp = x % 10;
x = x / 10;
result = result * 10 + tmp;
}

return result;
}
}


另外忘记一点, 对于 Math.abs(result) == Integer.MAX_VALUE / 10的情况, 也就是 214748364 , 因为Integer最大也就取到2147483647, 所以如果翻转后的整数取到了214748364, 并且还多一位的话, 那么这一位肯定是1或者2, 也就是Integer.MAX_VALUE的最高位, 2147483641, 2147483642都是不越界的

======================

我又开始刷题了
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  java leetcode