python,simple


  • 0
    class Solution(object):
        def nearestPalindromic(self, n):
            """
            :type n: str
            :rtype: str
            """
            if re.match(r'^1[0]*[01]$',n):
                res=""
                for i in range(len(n)-1):
                    res+="9"
                return  res
            #if n=="11" or n=="10":return "9"
            def makepalindorm(s):
                if len(s)==1: return s
                t=0
                for i in range(len(s)-1,(len(s)>>1)-1,-1):
                    s=s[:i]+s[t]+s[i+1:]
                    t+=1
                return s
            n0=makepalindorm(n)
            cur=(len(n)+1)>>1
            #if len(n)==2:cur=0
            n1=makepalindorm(str(int(n[:cur])+1)+n[cur:])
            n2=makepalindorm(str(int(n[:cur])-1)+n[cur:])
            print n0,n1,n2
            gap0=abs(int(n)-int(n0))
            gap1=abs(int(n)-int(n1))
            gap2=abs(int(n)-int(n2))
            print gap0,gap1,gap2
            if gap0==0:return n1 if gap1<gap2 else n2
            return n2 if gap2==min(gap0,gap1,gap2) else n0 if gap0==min(gap0,gap1,gap2) else n1
            
    

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.