Problem
Seventh Nearest Palindrome
Learn this problemProblem statement
You are given an integer n. Return the 7th nearest palindrome to n.
A valid palindrome for this problem must have at least two digits, so single-digit numbers from 1 to 9 are not considered.
Consider every valid palindrome p, including palindromes less than n, equal to n, and greater than n. Sort those palindromes by increasing distance |p - n|. If two palindromes have the same distance from n, place the greater palindrome first. Return the 7th palindrome in this order.
Function
seventhNearestPalindrome(n: long) → longExamples
Example 1
n = 100return = 131The nearest palindromes in order are 101, 99, 111, 88, 121, 77, 131. Therefore the 7th nearest palindrome is 131.
Example 2
n = 10return = 77Single-digit palindromes are ignored. The nearest valid palindromes are 11, 22, 33, 44, 55, 66, 77.
Constraints
1 ≤ n ≤ 1018- The input type is
long. - Single-digit numbers (1–9) are not considered valid palindromes.
- The solution should avoid scanning outward one number at a time, as the function may be called for many test cases.