I think the question is simple enough to understand.For more clarity I'm giving example :
In the list of 2 digit palindromes, the 7th palindrome is 77 (1st being 11, 2nd being 22 and so on).
Obviously a brute force solution exists but it's not efficient.
Can anyone suggest me some better solution to solve the problem ?
First, we can simplify the problem because we only need to look at the first half of the digits (rounding up if there are an odd number of digits). I will call the first set of digits significant digits and the rest non-significant digits.
This is because the non-significant digits must match the significant digits (in reverse). It is not possible to have another palindrome number with the same leading significant digits and different non-significant digits. The significant digits determine the entire palindrome number.
Now, we just need to come up with an algorithm to generate the nth valid significant digits. This would be easier if we allowed for leading zeros, so we'll come up with the algorithm that allows for leading zeros, then tweak the algorithm.
The first few palindromes (significant digits) would be:
So we can find the significant digits of the nth number by finding the decimal representation of (n-1).
To tweak the algorithm to work when not allowing leading zeros, we would start with a one as the leading digit:
This boils down to finding the decimal representation of (n-1) + 1000 = n + 999 and expanding into a full palindrome:
Example: Find the 113th palindrome of length 9.
On a side note, this algorithm could also be generalized to finding the nth palindrome of any ordered set of symbols (or alphabet).
Generalized algorithm:
Given: finding palindrome number n , palindrome has m symbols as digits , there are p symbols (10 symbols in decimal)
The first few 7-digit palindrome are:
I think it's very easy to see from the pattern of what is the nthm-digit palindrome...
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With