Problem
Given a 32-bit signed integer, reverse digits of an integer.
Example 1:
1 |
|
Example 2:
1 |
|
Example 3:
1 |
|
Note: Assume we are dealing with an environment which could only store integers within the 32-bit signed integer range: [−2^31, 2^31 − 1]. For the purpose of this problem, assume that your function returns 0 when the reversed integer overflows.
Explanation
-
We can get the reverse number by
res = res * 10 + num % 10; num/10
. -
To avoid overflow after we reverse the number, we can first check
Math.abs(res) > Integer.MAX_VALUE
, if this is true, we returnfalse
, otherwise, we use the above folmula to updateres
. -
Integer values will satisfy
-2147483648 to 2147483647
. We don’t need to checkMath.abs(res) == Integer.MAX_VALUE/10
because if this is the case, then the original inputx
’s right most digit must be 1 or 2 sinceres == Integer.MAX_VALUE/10
. Then, theres
may be2147483641
or2147483642
. But ifres = 2147483642
, then the originalx
is2463847412
which is greater than the range of integer, so ifMath.abs(res) == 214748364
, the originalx
must be1463847412
, so the reverse of thisx
is2147483641
and it’s in the range of integer, so we don’t need to check ifMath.abs(res) == 214748364
.
Solution
1 |
|