A/C Python solution, easy to understand, beat 4.53%


  • 0
    W
    def is_power2(self, num):
        return num != 0 and ((num & (num - 1)) == 0)
    
    def integerReplacement(self, n):
        """
        :type n: int
        :rtype: int
        """
        self.result = 0
        #print "n = ", n
    
        def helper(n):
            if n == 1:
                return 0
            elif self.is_power2(n) == True:
                i = 1
                k = 2
                while (k != n):
                    i += 1
                    k *= 2
    
                #print "i = ", i
                return i
    
            elif n % 2 == 0:
                return helper(n/2) + 1
    
            else:
                return 1 + min(helper(n-1), helper(n+1))
        res = helper(n)
        #print "res = ", res
        return res

Log in to reply
 

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