1. 程式人生 > >【LeetCode】338. Counting Bits

【LeetCode】338. Counting Bits

class Solution:
    # 遍歷
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        res = []
        for i in range(num+1):
            res.append(bin(i)[2:].count('1'))
        return res


class Solution:
    # 動態規劃
    def countBits(self, num):
        """
        :type num: int
        :rtype: List[int]
        """
        dp = [0]
        for i in range(1, num + 1):
            dp.append(dp[i & (i-1)] + 1)
        return dp