原题目为:
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321Have you thought about this? Here are some good questions to ask
before coding. Bonus points for you if you have already thought
through this!If the integer's last digit is 0, what should the output be? ie, cases
such as 10, 100.Did you notice that the reversed integer might overflow? Assume the
input is a 32-bit integer, then the reverse of 1000000003 overflows.
How should you handle such cases?For the purpose of this problem, assume that your function returns 0
when the reversed integer overflows.
难度: Easy
此题让我们输出给定一个整数的倒序数, 比如123倒序为321, -123倒序为-321. 但是如果倒序的过程中发生整型溢出, 我们就输出0.
倒序不复杂, 关键在于如何判定将要溢出.
最终AC的程序如下:
public class Solution {
public int reverse(int x) {
int x1 = Math.abs(x);
int rev = 0;
while (x1 > 0) {
if (rev > (Integer.MAX_VALUE - (x1 - (x1 / 10) * 10)) / 10) {
return 0;
}
rev = rev * 10 + (x1 - (x1 / 10) * 10);
x1 = x1 / 10;
}
if (x > 0) {
return rev;
} else {
return -rev;
}
}
}
其中 x1 - (x1 / 10) * 10
是获取x1的个位数字, 判定下一步是否将要溢出, 使用 rev > (Integer.MAX_VALUE - (x1 - (x1 / 10) * 10)) / 10
.
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。