Another python solution


  • 0
    J
    class Solution(object):
        def integerReplacement(self, n):
            """
            :type n: int
            :rtype: int
            """
            return self.helper(n, {})
        
        def helper(self, n, memo):
            if n == 1:
                return 0
            
            if n not in memo:
                if n % 2 == 0:
                    memo[n] = 1 + self.helper(n/2, memo)
                else:
                    memo[n] = min(1 + self.helper(n+1, memo), 1 + self.helper(n-1, memo))
            return memo[n]
    

Log in to reply
 

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