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.

解法1:

这里用到了其中一种判断是否overflow的办法,就是先存下变化之前的数,然后变化之后做相同的操作看看是否和原来的数字一致。如果不相等则说明这个操作overflow了。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
class Solution {
public int reverse(int x) {
int res = 0;
while ( x != 0) {
int newRes = res;
int digit = x % 10;
newRes = res * 10 + digit;
if ((newRes - digit) / 10 != res) {
// overflow
return 0;
}
res = newRes;
x /= 10;
}
return res;
}
}