564. Find the Closest Palindrome
一道數(shù)學(xué)題丈氓。。强法。重點(diǎn)是找到各種情況并且對(duì)其簡化万俗。分成兩種情況,第一種是如果S[:half] 的最后一個(gè)值 +(-1饮怯,0闰歪,1)然后翻轉(zhuǎn),第二種情況是如果要找的值和S不一樣長蓖墅,那么肯定是 "9...9"和“10..01”之間的一個(gè)
class Solution(object):
def nearestPalindromic(self, n):
"""
:type n: str
:rtype: str
"""
S = n
K = len(S)
candidates = [str(10**k + d) for k in (K-1, K) for d in (-1, 1)]
prefix = S[:(K+1)/2]
P = int(prefix)
for start in map(str, (P-1, P, P+1)):
candidates.append(start + (start[:-1] if K%2 else start)[::-1])
def delta(x):
return abs(int(S) - int(x))
ans = None
for cand in candidates:
if cand != S and not cand.startswith('00'):
if (ans is None or delta(cand) < delta(ans) or
delta(cand) == delta(ans) and int(cand) < int(ans)):
ans = cand
return ans