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.
題目分析:反轉(zhuǎn)一個數(shù)消约,例如,使123變?yōu)?21抹剩,-123變?yōu)?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;
}