File tree Expand file tree Collapse file tree 1 file changed +33
-0
lines changed
0564-find-the-closest-palindrome Expand file tree Collapse file tree 1 file changed +33
-0
lines changed Original file line number Diff line number Diff line change 1+ class Solution :
2+ def nearestPalindromic (self , n : str ) -> str :
3+ length = len (n )
4+ num = int (n )
5+
6+ # Edge cases for very small numbers
7+ if num == 0 :
8+ return "1"
9+ if num == 1 :
10+ return "0"
11+
12+ # Handle corner cases like "1000", "999"
13+ candidates = set ()
14+ candidates .add (str (10 ** (length - 1 ) - 1 )) # largest number with one less digit (e.g., 999 for 1000)
15+ candidates .add (str (10 ** length + 1 )) # smallest number with one more digit (e.g., 10001 for 9999)
16+
17+ # Generate the palindrome by mirroring
18+ prefix = int (n [:(length + 1 ) // 2 ])
19+ for i in [- 1 , 0 , 1 ]:
20+ new_prefix = str (prefix + i )
21+ if length % 2 == 0 :
22+ candidate = new_prefix + new_prefix [::- 1 ]
23+ else :
24+ candidate = new_prefix + new_prefix [:- 1 ][::- 1 ]
25+ candidates .add (candidate )
26+
27+ # Remove the original number from the candidates
28+ candidates .discard (n )
29+
30+ # Find the closest palindrome
31+ closest = min (candidates , key = lambda x : (abs (int (x ) - num ), int (x )))
32+
33+ return closest
You can’t perform that action at this time.
0 commit comments