Reverse digits of an integer.
Example1: x = 123, return 321Example2: x = -123, return -321
Have 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.
**Note:
**The input is assumed to be a 32-bit signed integer. Your function should return 0 when the reversed integer overflows.
题目分析:反转一个数,例如,使123变为321,-123变为-321,这题没什么难度,我怀疑做的是假的leetcode,唯一注意的一点就是整型溢出的问题。我们可以用一个double类型保存,然后再与整型界限比较。
public int reverse1(int x) {
if (x == 0)
return x;
long result = 0;
int temp = x;
while (temp != 0) {
result = result * 10 + temp % 10;
temp /= 10;
}
if (result < Integer.MAX_VALUE && result > Integer.MIN_VALUE)
return (int) result;
else
return 0;
}