[LeetCode] 7. Reverse Integer

Problem

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 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

  1. We can get the reverse number by res = res * 10 + num % 10; num/10.

  2. To avoid overflow after we reverse the number, we can first check Math.abs(res) > Integer.MAX_VALUE, if this is true, we return false, otherwise, we use the above folmula to update res.

  3. Integer values will satisfy -2147483648 to 2147483647. We don’t need to check Math.abs(res) == Integer.MAX_VALUE/10 because if this is the case, then the original input x’s right most digit must be 1 or 2 since res == Integer.MAX_VALUE/10. Then, the res may be 2147483641 or 2147483642. But if res = 2147483642, then the original x is 2463847412 which is greater than the range of integer, so if Math.abs(res) == 214748364, the original x must be 1463847412, so the reverse of this x is 2147483641 and it’s in the range of integer, so we don’t need to check if Math.abs(res) == 214748364.

Solution

1
2
3
4
5
6
7
8
9
10
11
12
class Solution {
    public int reverse(int x) {
        int res = 0;
        while (x != 0) {
            if (Math.abs(res) > Integer.MAX_VALUE/10) return 0;
            res = res * 10 + x % 10;
            x /= 10;
        }

        return res;
    }
}