Skip to content

Commit 3880973

Browse files
authored
Create find-the-closest-palindrome.py
1 parent 450f895 commit 3880973

File tree

1 file changed

+27
-0
lines changed

1 file changed

+27
-0
lines changed

Python/find-the-closest-palindrome.py

+27
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,27 @@
1+
# Time: O(l)
2+
# Space: O(l)
3+
4+
# Given an integer n, find the closest integer (not including itself), which is a palindrome.
5+
#
6+
# The 'closest' is defined as absolute difference minimized between two integers.
7+
#
8+
# Example 1:
9+
# Input: "123"
10+
# Output: "121"
11+
# Note:
12+
# The input n is a positive integer represented by string, whose length will not exceed 18.
13+
# If there is a tie, return the smaller one as answer.
14+
15+
class Solution(object):
16+
def nearestPalindromic(self, n):
17+
"""
18+
:type n: str
19+
:rtype: str
20+
"""
21+
l = len(n)
22+
candidates = set((str(10**l + 1), str(10**(l - 1) - 1)))
23+
prefix = int(n[:(l + 1)/2])
24+
for i in map(str, (prefix-1, prefix, prefix+1)):
25+
candidates.add(i + [i, i[:-1]][l%2][::-1])
26+
candidates.discard(n)
27+
return min(candidates, key=lambda x: (abs(int(x) - int(n)), int(x)))

0 commit comments

Comments
 (0)