Find the Closest Palindrome

Given a string n representing an integer, return the closest integer, not including itself, which is a palindrome. If there is a tie, return the smaller one.

The closest is defined as the absolute difference minimized between two integers.

Example 1
Inputn = "123"
Output"121"
The closest palindrome to 123, excluding itself, is 121.
Example 2
Inputn = "1"
Output"0"
0 and 2 are the closest palindromes but we return the smallest which is 0.

Constraints

  • 1 <= n.length <= 18
  • n consists of only digits.
  • n does not have leading zeros.
  • n is representing an integer in the range [1, 10^18 - 1].

Asked at 8 companies

</>

Your Solution

(Ctrl/Cmd + Enter)

Switching Language

Loading template...

Loading...

Sign in to save your progress

AI code evaluation

Get a correctness verdict, missed edge cases, and complexity analysis of your solution.

Sign in to evaluate