您的位置:首页 > 其它

[LeetCode 007] Reverse Integer

2016-02-17 07:32 369 查看

Reverse Integer

判断是否overflow的部分注意:

根据x的正负检测。

根据result不准确,我们需要检测x还剩一位数的时候result是否overflow

Implementation

public class Solution {
public int reverse(int x) {
int result = 0;
final int MIN_THRESHOLD = Integer.MIN_VALUE / 10;
final int MAX_THRESHOLD = Integer.MAX_VALUE / 10;
while (x != 0) {
int newResult = result * 10 + x % 10;
x = x / 10;
if (x > 0 && (newResult > MAX_THRESHOLD || (newResult == MAX_THRESHOLD && x > 7)))
return 0;
if (x < 0 && (newResult < MIN_THRESHOLD || (newResult == MIN_THRESHOLD && x < -8)))
return 0;
result = newResult;
}
return result;
}
}

public class Solution {
public int reverse(int x) {
int result = 0;
while (x != 0) {
int newResult = result * 10 + x % 10;
x = x / 10;
if (newResult / 10 != result) {
return 0;
}
result = newResult;
}
return result;
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: