Palindrome Number
Tell whether an integer reads the same backwards by reversing only the last half of its digits.
Given an integer xtruefalse
Example 1
Output: true
Example 2
Output: false
Explanation: backwards it reads "121-".
Example 3
Output: false
Explanation: backwards it reads "01".
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 % 1012321 % 10x / 1012321 / 10
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:
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
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 xintintInteger.MAX_VALUEint
Reversing 2,147,483,647 in an intlong
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
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
This stop also keeps the reversed half small. An int
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
Java Solution
The method isPalindrome
- First, return
whenfalse is negative, or whenx andx % 10 == 0 is not 0.x - Start a variable
at 0. AreversedHalf loop runs as long aswhile . Each pass appends the last digit ofx > reversedHalf tox withreversedHalf , then drops that digit fromreversedHalf * 10 + x % 10 withx .x /= 10 - After the loop, return
iftrue equalsx (an even number of digits) or equalsreversedHalf (an odd number, with the middle digit dropped).reversedHalf / 10
The mainint
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:
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 -> false100 -> false-2147483648 -> false
The number 100 needs that first check. A version of the method without the test for a last 0 returned truexreversedHalfreversedHalf / 10
The lines 0 -> true7 -> truexreversedHalf
Now look at 2147447412 -> truexreversedHalfreversedHalf2147483647 -> falsexreversedHalfint
Complexity
Only about half the digits move, and each one costs a single pass of the loop.
- Time: O(log x), because
has about log10 x decimal digits and each pass of the loop moves one of them, stopping near the middle.x - Space: O(1), because the method keeps a single extra
,int , and never builds a string or an array of digits.reversedHalf
Reversing all the digits of a number while guarding against overflow is the topic of