1. 程式人生 > >python leetcode 397. Integer Replacement

python leetcode 397. Integer Replacement

關鍵是要找到奇數時n+1的情況:n+1是4的倍數
例如23
n-1的情況:23->22->11->10->5->4->2->1
n-1的情況:23->24->12->6->3->2->1

class Solution(object):
    def integerReplacement(self, n):
        """
        :type n: int
        :rtype: int
        """
        def isP(n):
            n=n+1
            return n%4==0
        count=0
        while n>1:
            count+=1
            if n&1==0:
                n=n//2
            else:
                if isP(n) and n!=3:
                    n=n+1 
                else:
                    n-=1 
        return count