Reverse Integer

Turn an int around digit by digit, and return 0 when the reversed number no longer fits in an int.

Given a 32-bit signed integer x, return the number with its digits in reverse order, keeping its sign. If the reversed number is outside the 32-bit range, from -231 to 231 - 1, return 0 instead. Assume the code may not use 64-bit integers, so a long is not allowed.

Example 1
Input: x = 123
Output: 321
Example 2
Input: x = -123
Output: -321
Example 3
Input: x = 120
Output: 21
Example 4
Input: x = 1534236469
Output: 0
Explanation: 9646324351 does not fit in 32 bits.
Solution

The Idea

On paper, reversing 123 is easy: read it from the right and write 321. A program holds 123 as a number, though, not as three written characters. So how does it reach the digits one at a time, starting from the right?

Dividing by 10 does it. The remainder of 123 divided by 10 is 3, the digit on the right, and Java writes that remainder as 123 % 10. The whole-number part, 123 / 10, is 12, which is 123 with that digit removed. Doing it again on 12 gives 2 and leaves 1.

Building the answer works the other way round. Start with 0. To add a digit on the right, multiply what you have by 10 and add the digit. So 0 becomes 3, then 3 × 10 + 2 = 32, then 32 × 10 + 1 = 321. Adding a digit this way is called pushing it onto the result. Here is the whole run for Example 1:

Reversing 123: step 1 takes the last digit 3 and result becomes 3, step 2 takes 2 and result becomes 32, step 3 takes 1 and result becomes 321. For 1534236469, before pushing its final digit, 1, the result so far is 964632435, which is larger than the largest int divided by 10, 214748364, so the method returns 0.

In the top part of the picture, the column "x left" shrinks from 123 to 12 to 1. The column "last digit (x % 10)" reads 3, 2, 1, and "result so far" grows from 3 to 32 to 321. Example 3 works the same way: 120 gives the digit 0 first, and 0 × 10 + 0 is still 0, so the zero simply disappears and the answer is 21.

Example 4 raises the harder question. The reverse of 1534236469 is 9,646,324,351, but the largest value a Java int can store is 2,147,483,647. How can the program notice that the answer is too big, when it cannot store the too-big answer anywhere?

It can check one step early. Look at the bottom part of the picture. Before pushing the final digit, 1, the result so far is 964632435. Multiplying it by 10 would give more than nine billion. Any result so far that is larger than the largest int divided by 10, which is 214748364, gives a product too big for an int. Since 964632435 > 214748364, the answer cannot fit, and the method returns 0 without ever doing the multiplication.

Solution Approach

Three things are left to settle: how negative numbers are handled, exactly when a push would go past the int range, and why the check has to come before the push.

Negative numbers

Does -123 need its own branch? In Java it does not. -123 % 10 is -3 and -123 / 10 is -12, so every digit simply comes out negative. Pushing -3, -2 and -1 builds -3, then -32, then -321, which is Example 2's answer with the sign already in place.

When a push goes out of range

Which values of the result so far are safe to push onto? The top of the range is 2147483647, and Integer.MAX_VALUE / 10 is 214748364. If the result so far is bigger than 214748364, times 10 is already too big. If it equals 214748364, times 10 is 2147483640, and the digit can add at most 7 before passing 2147483647.

The bottom of the range is -2147483648, one further from zero than the top. Integer.MIN_VALUE / 10 is -214748364, so a result below that fails, and a result equal to it allows a digit down to -8 but not -9.

Checking before the push

Why not push first and test the answer afterwards? Because by then the value is already wrong. When an int calculation passes 2147483647, Java keeps only the low 32 bits of the true result, and the number wraps around into a different value. A version without any check returns 1056389759 for 1534236469, a number that looks perfectly normal.

With a long the program could hold 9,646,324,351 and compare it with the limit afterwards, but this problem rules that out. Comparing the result so far with the largest int divided by 10 needs only int values that always fit.

Java Solution

The method reverse works in these steps:

  1. First, set up result as 0. It holds the digits reversed so far.
  2. Start a loop that runs while x is not 0. Inside it, take the last digit into digit with x % 10, and drop that digit from x with x /= 10.
  3. Before pushing, compare result with Integer.MAX_VALUE / 10. If it is bigger, or equal with a digit above 7, return 0.
  4. Make the same check on the negative side, against Integer.MIN_VALUE / 10 and a digit below -8, and return 0 if it fails.
  5. Push the digit with result = result * 10 + digit. When x reaches 0, the loop ends and the method returns result.

The main method runs the four examples, then 0, two inputs whose reverse lands just inside the range, and the two ends of the range themselves.

Java
public class ReverseInteger {

    public static int reverse(int x) {
        int result = 0;
        while (x != 0) {
            int digit = x % 10;               // last digit, with the sign of x: -123 % 10 == -3
            x /= 10;                          // drop that digit
            if (result > Integer.MAX_VALUE / 10
                    || (result == Integer.MAX_VALUE / 10 && digit > 7)) {
                return 0;                     // result * 10 + digit would pass 2147483647
            }
            if (result < Integer.MIN_VALUE / 10
                    || (result == Integer.MIN_VALUE / 10 && digit < -8)) {
                return 0;                     // result * 10 + digit would pass -2147483648
            }
            result = result * 10 + digit;
        }
        return result;
    }

    public static void main(String[] args) {
        int[] inputs = {123, -123, 120, 1534236469, 0, 1463847412, -2147483412,
                Integer.MAX_VALUE, Integer.MIN_VALUE};
        for (int x : inputs) {
            System.out.println(x + " -> " + reverse(x));
        }
    }
}

Running it prints:

Output
123 -> 321
-123 -> -321
120 -> 21
1534236469 -> 0
0 -> 0
1463847412 -> 2147483641
-2147483412 -> -2143847412
2147483647 -> 0
-2147483648 -> 0

The four examples come out as 321, -321, 21 and 0. For 0 the loop never runs, so result stays 0.

Look at 1463847412 -> 2147483641. Before its final push, result equals 214748364, exactly the limit, and the digit is 1, so the check lets it through and the answer lands six below the top of the range. The line for -2147483412 is a ten-digit negative input whose reverse, -2143847412, still fits, so neither check stops it.

The last two lines are the ends of the range. Reversed, 2147483647 would be 7,463,847,412 and -2147483648 would be -8,463,847,412, both far outside, so both return 0.

Complexity

The method does a fixed amount of work for each digit of x.

  • Time: O(log |x|), because the loop removes one decimal digit of x per pass, and an int has at most 10 of them.
  • Space: O(1), because the method keeps only result and digit and never turns the number into a string or an array of digits.

Palindrome Number pushes digits the same way, but reverses only half of them, so its result never gets near the limit.