TommyCpp / AhaMoment

Note, Practice project, leetcode and other stuff.
1 stars 3 forks source link

338. Counting Bits #1

Closed TommyCpp closed 6 years ago

TommyCpp commented 6 years ago

https://leetcode.com/problems/counting-bits/description/

TommyCpp commented 6 years ago

超过最大递归深度

class Solution:
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        if num == 0:
            return [0]
        else:
            lst = self.countBits(num - 1)
            log = math.log2(num)
            if log.is_integer():
                lst.append(1)
            else:
                lst.append(lst[num - 2**int(log)] + 1)
            return lst
TommyCpp commented 6 years ago

实际上针对数字的乘除2可以使用位操作来替代