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:
- 1: 0000
- 2: 0001
- 3: 0002
- ...
- 100: 0099
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:
- 1: 1000
- 2: 1001
- 3: 1002
- ...
- 100: 1099
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.
- Determine number of digits to look at: Round up(9 / 2) = 5 --> only look at first 5 digits.
- Find number to add to get rid of leading zeros: 10^(5-1) = 10000
- Use formula: (113 - 1) + 10000 = 10112
- Expanded into palindrome: 101121101
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)
- Let q = ceiling(m / 2)
- Let offset = p ^ (q - 1)
- Let number = (n - 1) + offset
- Let answer be number expanded as a palindrome