Python | Leetcode Python题解之第564题寻找最近的回文数
题目:
题解:
class Solution:
def nearestPalindromic(self, n: str) -> str:
m = len(n)
candidates = [10 ** (m - 1) - 1, 10 ** m + 1]
selfPrefix = int(n[:(m + 1) // 2])
for x in range(selfPrefix - 1, selfPrefix + 2):
y = x if m % 2 == 0 else x // 10
while y:
x = x * 10 + y % 10
y //= 10
candidates.append(x)
ans = -1
selfNumber = int(n)
for candidate in candidates:
if candidate != selfNumber:
if ans == -1 or \
abs(candidate - selfNumber) < abs(ans - selfNumber) or \
abs(candidate - selfNumber) == abs(ans - selfNumber) and candidate < ans:
ans = candidate
return str(ans)
原文地址:https://blog.csdn.net/Mopes__/article/details/143826976
免责声明:本站文章内容转载自网络资源,如本站内容侵犯了原著者的合法权益,可联系本站删除。更多内容请关注自学内容网(zxcms.com)!