leetcode [python] 【338】Counting Bits

why小曼發表於2016-04-07

思路一:發現數字規律求解:

1: 1

2,3: 1,2

4,5,6,7: 1,2,2,3

class Solution(object):
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        
        nums = [0]
        if num == 0:
            return nums
        a = int(math.log(num,2))
        temp =[1]
        for i in range(a):
            nums.extend(temp)
            temp = temp + [ele+1 for ele in temp]
        b = num - int(math.pow(2,a)) + 1 
        nums.extend(temp[:b])
        return nums

思路二:利用奇偶性:

對於一個奇數,二進位制中1的個數等於其折半數的二進位制中1的個數加1

所以只需將一個數除以2,判斷最低位是否為1

所以可以有遞推公式 res[i] = res[i/2] + (i&1),這裡i/2等價於i>>1

class Solution(object):
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        
        res = [0] * (num + 1)
        for i in xrange(1,num + 1):
            res[i] = res[i/2] + (i & 1)
        return res

思路三:利用最高位:

11(3) = 8(1) + 3(2) 一個數分解為最大2的整數冪和X

class Solution(object):
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        
        res = [0] * (num + 1)
        for i in range(1,num + 1):
            res[i] = res[i - (1<<int(math.log(i,2)))] + 1
        return res



相關文章