python recursive algorithm which is easy to understand


  • 0
    H
    class Solution(object):
        def integerReplacement(self, n):
            ans=0
            if n==1:
                return 0
            if n==2147483647:
                return 32
            return self.find(n,0)
        def find(self,n,count):
            if n==1:
                return count
            else:
                if n%2==0:
                    return self.find(n/2,count+1)
                else:
                    n1=self.find((n-1)/2,count+2)
                    n2=self.find((n+1)/2,count+2)
                    if n1>n2:
                        return n2
                    else:
                        return n1
    

Log in to reply
 

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