[LeetCode] 7. Reverse Integer ☆
Reverse digits of an integer.
Example1:
x = 123, return 321
Example2:
x = -123, return -321
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.
Note:
The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
解法:
翻转数字问题需要注意的就是溢出问题,为什么会存在溢出问题呢,我们知道int型的数值范围是 -2147483648~2147483647, 那么如果我们要翻转 1000000009 这个在范围内的数得到 9000000001,而翻转后的数就超过了范围。
因此,可以采用double类型存储翻转后的数,再与 Integer.MAX_VALUE 和 Integer.MIN_VALUE 比较,判断是否溢出。
此处并不需要在意正负数的情况,对结果没有影响,因为:12 % 10 = 2; -12 % 10 = -2
public class Solution { public int reverse(int x) { double res = 0; while (x != 0) { res = res * 10 + x % 10; x /= 10; } if (res > Integer.MAX_VALUE || res < Integer.MIN_VALUE) return 0; else return (int)res; } }