class Solution: def nearestPalindromic(self, n): """ :type n: str :rtype: str """ b=list(n) c=list(n) e=list(n) l=len(n) if (l%2==0): mid=l//2 else: mid=l//2+1 if (int(n)<=10): return (str(int(n)-1)) if n==‘11‘: return (‘9‘) else: #equal for x in range(mid): if (b[x]!=b[l-x-1]): b[l-x-1]=b[x] f=‘‘.join(b) #print(f) #larger d=str(int(n[0:mid])+1) if len(d)>mid: c.append(‘0‘) for y in range(len(d)): c[y]=d[y] if (c[y]!=c[l-y]): c[l-y]=c[y] else: for y in range(len(d)): c[y]=d[y] if (c[y]!=c[l-y-1]): c[l-y-1]=c[y] g=‘‘.join(c) #print(g) #smaller d=str(int(n[0:mid])-1) if len(d)<mid: e.pop() for z in range(len(d)): e[z]=d[z] if (e[z]!=e[l-z-2]): e[l-z-2]=e[z] e[len(d)]=d[len(d)-1] else: for z in range(len(d)): e[z]=d[z] if (e[z]!=e[l-z-1]): e[l-z-1]=e[z] h=‘‘.join(e) #print(h) #print(‘***************************‘) rf=abs(int(f)-int(n)) rg=abs(int(g)-int(n)) rh=abs(int(h)-int(n)) if f==n: if (rg<rh): return (g) else: return (h) else: if rf==rh: return (str(min(int(f),int(h)))) else: r=[rf,rg,rh] t=r.index(min(r)) if t==0: return (f) elif t==1: return (g) else: return (h)
原文地址:https://www.cnblogs.com/jiage666/p/9745784.html
时间: 2024-11-09 00:49:55