classSolution:defnearestPalindromic(self, n:str)->str:
m =len(n)
candidates =[10**(m -1)-1,10** m +1]
selfPrefix =int(n[:(m +1)//2])for x inrange(selfPrefix -1, selfPrefix +2):
y = x if m %2==0else x //10while 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 ==-1or \
abs(candidate - selfNumber)<abs(ans - selfNumber)or \
abs(candidate - selfNumber)==abs(ans - selfNumber)and candidate < ans:
ans = candidate
returnstr(ans)