7. reverse integer

Given a 32-bit signed integer, reverse digits of an integer.

Example 1:

1
2
Input: 123
Output: 321

Example 2:

1
2
Input: -123
Output: -321

Example 3:

1
2
Input: 120
Output: 21

数字反转。

分析:题目不难,唯一需要注意的就是反转后是否越界的问题,所以不能定义int的变量接收反转后的值,应该用long,详细代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
class  {
public int reverse(int x) {
long num = 0;
while (x != 0) {
num = num *10 + x % 10;
x = x / 10;
}
if (num >= Integer.MAX_VALUE || num <= Integer.MIN_VALUE) {
return 0;
}
return (int)num;
}
}