题目:
题解:
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 // 10while y:x = x * 10 + y % 10y //= 10candidates.append(x)ans = -1selfNumber = 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 = candidatereturn str(ans)