原题目为:java
Reverse digits of an integer.
Example1: x = 123, return 321
Example2: x = -123, return -321gitHave you thought about this? Here are some good questions to ask
before coding. Bonus points for you if you have already thought
through this!thisIf the integer's last digit is 0, what should the output be? ie, cases
such as 10, 100.codeDid 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?inputFor the purpose of this problem, assume that your function returns 0
when the reversed integer overflows.it
难度: Easyio
此题让咱们输出给定一个整数的倒序数, 好比123倒序为321, -123倒序为-321. 可是若是倒序的过程当中发生整型溢出, 咱们就输出0.ast
倒序不复杂, 关键在于如何断定将要溢出.function
最终AC的程序以下:class
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
.