Skip to content

Commit c44d25a

Browse files
committed
Time: 39 ms (36.42%), Space: 16.5 MB (67.95%) - LeetHub
1 parent b45f3e4 commit c44d25a

File tree

1 file changed

+45
-0
lines changed

1 file changed

+45
-0
lines changed
Lines changed: 45 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,45 @@
1+
# time complexity: O(n)
2+
# space complexity: O(n)
3+
class Solution:
4+
def nearestPalindromic(self, n: str) -> str:
5+
lenN = len(n)
6+
i = lenN // 2 - 1 if lenN % 2 == 0 else lenN // 2
7+
firstHalf = int(n[: i + 1])
8+
possibilities = []
9+
possibilities.append(
10+
self.halfToPalindrome(firstHalf, lenN % 2 == 0)
11+
)
12+
possibilities.append(
13+
self.halfToPalindrome(firstHalf + 1, lenN % 2 == 0)
14+
)
15+
possibilities.append(
16+
self.halfToPalindrome(firstHalf - 1, lenN % 2 == 0)
17+
)
18+
possibilities.append(10 ** (lenN - 1) - 1)
19+
possibilities.append(10**lenN + 1)
20+
21+
diff = float("inf")
22+
res = 0
23+
nl = int(n)
24+
for cand in possibilities:
25+
if cand == nl:
26+
continue
27+
if abs(cand - nl) < diff:
28+
diff = abs(cand - nl)
29+
res = cand
30+
elif abs(cand - nl) == diff:
31+
res = min(res, cand)
32+
return str(res)
33+
34+
def halfToPalindrome(self, left: int, even: bool) -> int:
35+
res = left
36+
if not even:
37+
left = left // 10
38+
while left > 0:
39+
res = res * 10 + left % 10
40+
left //= 10
41+
return res
42+
43+
44+
n = "123"
45+
print(Solution().nearestPalindromic(n))

0 commit comments

Comments
 (0)