hardMath / GeometryPure DSA~40 min
Closest Palindromic Number
A config validator nudges a numeric token to the nearest palindrome (for symmetric checksum codes). Given the number as a string, return the closest palindrome that is not equal to it; on a tie pick the smaller.
Problem
Given a numeric string n (no leading zeros), return the closest integer (as a string) that is a palindrome and not equal to n. If two palindromes are equally close, return the smaller one.
Input
A string n representing a positive integer without leading zeros.
Output
A string: the closest palindrome different from n.
Constraints
- 1 <= n.length <= 18
- n consists of digits and represents a value in [1, 10^18 - 1].
Examples
Example 1
Input
n = "123"
Output
"121"
121 is the nearest palindrome to 123.
Example 2
Input
n = "1"
Output
"0"
The closest palindrome not equal to 1 is 0.