> For the complete documentation index, see [llms.txt](https://cai-sen-se.gitbook.io/leetcode/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://cai-sen-se.gitbook.io/leetcode/201-400/338.-bi-te-wei-ji-shu.md).

# 338. 比特位计数

<https://leetcode-cn.com/problems/counting-bits/>

## 解法一：dp

当num=5时

```
二进制   1个数
  0 --> 0
  1 --> 1
 10 --> 1
 11 --> 2
100 --> 1
101 --> 2
```

发现规律,后面的数可以利用前面的结果(动态规划,或者叫备忘录).例如数字5,二进制为101,可以将其分为两部分:

(1)最后一位,为1,可以用5%2获得

(2)剩余的数,为10(二进制),可以用5/2=2获得(即右移一位) 则5的bits等于2的bits加上1,即1+1=2.

推广可知,记i的Counting Bits为res\[i]，则 res\[i] = res\[i/2] + i%2

```python
class Solution:
    def countBits(self, num: int) -> List[int]:
        dp = [0] * (num+1)
        if num == 0:    #边界
            return dp
        #初始化
        dp[0], dp[1] = 0, 1
        for i in range(2, num+1):
            dp[i] = dp[i//2] + i%2
        return dp
```
