Consider every positive integer that is an even-length palindrome and uses only the digits 1 and 2. Sort them in increasing numeric order: 11, 22, 1111, 1221, 2112, 2222, 111111, ...
Given an integer n (1-indexed), return the nth number in this sequence as a string.
Odd-length palindromes are not part of the sequence.
Function Signature
def nth_even_palindrome(n: int) -> str:
Rules
-
The sequence holds only palindromes with an even number of digits, and every digit is
1
or
2
.
-
Values are ordered by numeric value, and
n = 1
refers to
11
.
-
Return the decimal digits as a string. The answer can be far longer than a 64-bit integer allows.
Constraints
-
1 <= n <= 10^12
-
n
can be larger than the 32-bit integer range, so it needs a 64-bit integer type in languages with fixed-width integers.
Examples
Input: n = 4
Output: "1221"
The sequence begins 11, 22, 1111, 1221, so the 4th value is "1221".
Input: n = 7
Output: "111111"
The six palindromes of length 2 and 4 are 11, 22, 1111, 1221, 2112, 2222. The 7th value is the smallest one of length 6, which is "111111".
Input: n = 10
Output: "122221"
The length-6 values start at position 7 and run 111111, 112211, 121121, 122221 in increasing order, so position 10 is "122221".