Problem
Seventh Nearest Palindrome
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.
Examples
01 · Example 1
n = 100 return = 131
The nearest palindromes in order are 101, 99, 111, 88, 121, 77, 131. Therefore the 7th nearest palindrome is 131.
02 · Example 2
n = 10 return = 77
Single-digit palindromes are ignored. The nearest valid palindromes are 11, 22, 33, 44, 55, 66, 77.
Constraints
1 <= n <= 10^9- The function may be called for many test cases, so the solution should avoid scanning outward one number at a time.
More Deloitte problems
public long seventhNearestPalindrome(long n) {
// write your code here
}n100
expected131
sign in to submit