Palindrome Number

Tell whether an integer reads the same backwards by reversing only the last half of its digits.

Given an integer x, return true if its digits read the same from right to left as from left to right, and false otherwise. Solve it with arithmetic, without turning the number into a string.

Example 1
Input: x = 121
Output: true
Example 2
Input: x = -121
Output: false
Explanation: backwards it reads "121-".
Example 3
Input: x = 10
Output: false
Explanation: backwards it reads "01".
Solution

The Idea

Read 121 from the left and you say one, two, one. Read it from the right and you say the same three digits. A number that survives this test, like the word "level" does, is a palindrome. 123 fails it, because from the right it reads 321.

Examples 2 and 3 show two more ways to fail. In -121 the minus sign would end up at the back, as "121-". In 10 the 0 would end up at the front, as "01", and no number is written with a leading 0. So every negative number fails, and so does every number whose last digit is 0, apart from 0 itself.

That leaves the real question: how do we read a number backwards without making it a string? Two pieces of arithmetic do it. The remainder after dividing by 10, x % 10, is the last digit, so 12321 % 10 is 1. Whole-number division by 10, x / 10, drops that digit, so 12321 / 10 is 1232. Take the last digit off again and again, and append each one to a second number: multiply that number by 10, then add the digit. The digits arrive in reverse order.

Do we have to reverse every digit, though? In a palindrome, the back half read backwards is exactly the front half. So it is enough to move digits until the middle is reached, and then compare what is left with what was built. The picture follows 12321 digit by digit:

Checking 12321: the last digit of x moves to the reversed half three times, giving 1232 and 1, 123 and 12, then 12 and 123. The loop stops, the middle digit 3 is dropped with 123 / 10 = 12, and 12 equals 12.

In the row labelled "start", the blue boxes hold all of 12321, with the middle digit 3 in orange, and the reversed half is empty. Each row below moves one digit across: 1232 and 1, then 123 and 12, then 12 and 123. In the row labelled "3 digits moved", what is left of x, 12, is no longer larger than the reversed half, 123, so the middle has been reached.

The orange 3 is the middle digit. It now sits at the end of the reversed half, and it matches itself whatever it is, so it can be dropped: 123 / 10 is 12. The front half 12 equals the reversed back half 12, so 12321 is a palindrome. For 1221, which has an even number of digits, the steps give 122 and 1, then 12 and 12, and the two halves are compared directly.

Solution Approach

Reversing the whole number is the simple way, and it breaks on large inputs. Reversing only the back half avoids that, and it needs three decisions: which numbers to turn away first, how the loop knows it has reached the middle, and how to compare the two halves.

Reversing the whole number

Why not reverse all the digits and compare the result with x? For most inputs that works, but the reverse of a large int may not fit back into an int. Integer.MAX_VALUE, 2,147,483,647, is the largest value an int can store, and its own reverse is 7,463,847,412.

Reversing 2,147,483,647 in an int therefore overflows. Java reports no error and keeps only the low 32 bits of the true result, so our test run of a full reversal printed -1,126,087,180. Doing the reversal in a long would work, but reversing only half avoids large numbers altogether.

Numbers to turn away first

Which numbers can be rejected before any digit moves? A negative number cannot be a palindrome, because of its minus sign. A number whose last digit is 0 cannot be one either, unless it is 0, since its reverse would need a leading 0. The test x % 10 == 0 finds that last 0.

Knowing when the middle is reached

How does the loop know it has moved half the digits, without counting them first? It keeps moving digits while what is left of x is larger than the reversed half. For 1221 the two sides become equal at 12 and 12. For 12321 the reversed half overtakes at 123, one digit longer than the 12 on the left.

This stop also keeps the reversed half small. An int has at most 10 digits, and the loop stops after moving at most 6 of them, so the reversed half stays below 1,000,000 and never overflows. Over 30 million test inputs, the largest it reached was 214,734.

Comparing the two halves

What is left to compare when the loop ends? For a palindrome with an even number of digits, the two halves end the loop with the same length and the same value, like 12 and 12 for 1221. With an odd number of digits, the reversed half carries the middle digit at its end, so it is divided by 10 before comparing. The method returns true when either comparison holds.

Java Solution

The method isPalindrome works in these steps:

  1. First, return false when x is negative, or when x % 10 == 0 and x is not 0.
  2. Start a variable reversedHalf at 0. A while loop runs as long as x > reversedHalf. Each pass appends the last digit of x to reversedHalf with reversedHalf * 10 + x % 10, then drops that digit from x with x /= 10.
  3. After the loop, return true if x equals reversedHalf (an even number of digits) or equals reversedHalf / 10 (an odd number, with the middle digit dropped).

The main method checks the three examples, 1221 and 12321, then 0, a single digit, 100, the 10-digit palindrome 2,147,447,412, and both ends of the int range.

Java
public class PalindromeNumber {

    public static boolean isPalindrome(int x) {
        if (x < 0 || (x % 10 == 0 && x != 0)) {
            return false;                     // a minus sign, or a last digit 0 with no first 0
        }
        int reversedHalf = 0;
        while (x > reversedHalf) {            // stop once half the digits have moved across
            reversedHalf = reversedHalf * 10 + x % 10;   // take the last digit of x
            x /= 10;                                     // and drop it from x
        }
        return x == reversedHalf || x == reversedHalf / 10;   // even or odd digit count
    }

    public static void main(String[] args) {
        int[] tests = {121, -121, 10, 1221, 12321, 0, 7, 100, 2147447412,
                       Integer.MAX_VALUE, Integer.MIN_VALUE};
        for (int x : tests) {
            System.out.println(x + " -> " + isPalindrome(x));
        }
    }
}

Running it prints:

Output
121 -> true
-121 -> false
10 -> false
1221 -> true
12321 -> true
0 -> true
7 -> true
100 -> false
2147447412 -> true
2147483647 -> false
-2147483648 -> false

Look at -121 -> false and 100 -> false: both come from the first check, so the loop never runs for them. The last line, -2147483648 -> false, is turned away by its sign in the same way.

The number 100 needs that first check. A version of the method without the test for a last 0 returned true for 10, 100 and 1000 in our run. For 10 it moves the 0 across, then the 1, and ends with x = 0 and reversedHalf = 1. The comparison with reversedHalf / 10 then sees 0 equal to 1 / 10, which is 0, and reports a palindrome.

The lines 0 -> true and 7 -> true show the smallest cases. For 0 the loop does not start, because 0 is not larger than 0, and 0 equals 0. For 7 one pass leaves x = 0 and reversedHalf = 7, and 0 equals 7 / 10.

Now look at 2147447412 -> true. A trace of the loop for that input ends with x and reversedHalf both at 21474, so reversedHalf never grew past five digits. For 2147483647 -> false the trace ends with x = 21474 and reversedHalf = 74638, again well inside the int range.

Complexity

Only about half the digits move, and each one costs a single pass of the loop.

  • Time: O(log x), because x has about log10 x decimal digits and each pass of the loop moves one of them, stopping near the middle.
  • Space: O(1), because the method keeps a single extra int, reversedHalf, and never builds a string or an array of digits.

Reversing all the digits of a number while guarding against overflow is the topic of Reverse Integer.