leetcode 7 reverse integer

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

Note:
Assume we are dealing with an environment which could only hold integers within the 32-bit signed integer range. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.


将int类型的数字翻转过来。按最简单的模10处理。

注意:倒转过来的时候,可能会导致溢出问题。

int类型的范围是[-65536, 65535]

例如: 一个数为10009,倒过来为90001,就会导致溢出。

​ 同理一个数为-10009,同样也会导致溢出。

所以需要问清楚,当溢出时返回结果是什么。


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