导航
导航
文章目录
  1. 题目
  2. 翻译

LeetCode-7.Reverse Integer

题目

Reverse digits of an integer.

Example1: x = 123, return 321
Example2: 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.

翻译

反转一个整数的各位。
例1:x=123,返回321;
例2:x=-123,返回-321。

你想过吗?
这里有一些在编码前的好问题,如果你已经想到了可以得到额外分数!
如果整数的最后一位是0,返回是什么?例如,10,100。
你是否注意到反转后的数字可能溢出?例如输入是一个32位的整数,那么1000000003的反转数溢出,你怎样处理这样的情况?
当反转数溢出时返回0。

需要注意的是负数的情况,以及反转越界的情况:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public class Solution {
public int reverse(int x) {
int revNum = 0, flag = x >= 0 ? 1 : -1;
x *= flag;

while (x > 0) {
int low = x % 10;
// 检查越界
if (revNum > Integer.MAX_VALUE / 10 || Integer.MAX_VALUE - revNum * 10 < low)
return 0;
revNum = revNum * 10 + low;
x /= 10;
}

return revNum * flag;
}
}