Given a string n that represents a positive integer, return the closest integer to it that is a palindrome, not counting n itself. Closest means the absolute difference between the two integers is as small as possible. If two palindromes are equally close, return the smaller one.
Function Signature
def nearest_palindrome(n: str) -> str:
Rules
-
Return the answer as a decimal string with no leading zeros, for example
"121"
or
"0"
.
-
A palindrome is a non-negative integer whose decimal digits read the same forwards and backwards. Every single-digit number, including
0
, is a palindrome.
-
The answer must differ from the integer
n
, even when
n
is itself a palindrome.
-
When two palindromes are at the same distance from
n
, return the smaller one.
Constraints
-
1 <= len(n) <= 18
-
n
consists only of digits and has no leading zeros.
-
n
represents an integer from
1
to
10^18 - 1
.
Examples
Input: n = "123"
Output: "121"
121 is 2 away from 123. The next palindrome above, 131, is 8 away.
Input: n = "1"
Output: "0"
1 itself is excluded. Both 0 and 2 are 1 away, and the tie goes to the smaller value, 0.
Input: n = "100"
Output: "99"
99 and 101 are both 1 away from 100, so the smaller one, 99, is returned.