-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmain.py
34 lines (28 loc) · 839 Bytes
/
main.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
class Solution:
def nearestPalindromic(self, s: str) -> str:
n = len(s)
t = int(s)
def mirrow(l):
result = l
if n % 2 == 1:
l //= 10
while l > 0:
result = result * 10 + l % 10
l //= 10
return result
left = int(s[:(n + 1) // 2])
candidates = [
10**(n - 1) - 1,
10**n + 1,
mirrow(left),
mirrow(left + 1),
mirrow(left - 1),
]
result, min_diff = float('inf'), float('inf')
for v in candidates:
diff = abs(t - v)
if v == t:
continue
if (diff < min_diff) or (diff == min_diff and v < result):
result, min_diff = v, diff
return str(result)