#564

Find the Closest Palindrome

international master · 2000 · lc hard +32 · verified · 31.9% accepted · 1,322 likes · top 9%

play →

Description

Given a string n that encodes a positive integer, find the nearest palindrome — an integer other than n itself that reads the same forwards and backwards — minimizing the absolute difference. Break ties by returning the smaller value.

Example 1:

Input: n = "123"
Output: "121"

Example 2:

Input: n = "1"
Output: "0"
Explanation: 0 and 2 are the closest palindromes but we return the smallest which is 0.

Code

1
2
3