LeetCode 338 Counting Bits (Python)

Posted by 小明MaxMing on May 28, 2020

题目

Given a non negative integer number num. For every numbers i in the range 0 ≤ i ≤ num calculate the number of 1’s in their binary representation and return them as an array.

解题思路

对于一个数i转换成二进制之后1的个数,如果i是偶数,则和i/2的个数相同,如果i是奇数,则为i/2的个数加1

代码

class Solution:
    def countBits(self, num: int) -> List[int]:
        res = [0] * (num + 1)
        for i in range(num + 1):
            res[i] = res[i >> 1] + (i & 1)
        return res

视频讲解 YouTube<--欢迎点击订阅

视频讲解 bilibili<--欢迎点击订阅