Create 338. Counting Bits.md

This commit is contained in:
ShusenTang 2019-12-10 15:32:48 +08:00 committed by GitHub
parent b0f74b0d47
commit cd6fe8055a
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23

View File

@ -0,0 +1,25 @@
# [338. Counting Bits](https://leetcode.com/problems/counting-bits/)
# 思路
这道题给我们一个整数n然我们统计从0到n每个数的二进制中的1的个数存入一个一维数组中返回。
设结果数组为`res`,那么问题的关键就在于`res[i]`怎样从`res[0,...,i-1]`快速计算得出。有很多思路,例如
* `res[i] = res[i / 2] + (i & 1)`: i 为偶数时`res[i] = res[i / 2]`否则`res[i] = res[i / 2] + 1`
* `res[i] = res[i & (i-1)] + 1`: 因为`i & (i-1)`表示去掉二进制中末尾1后的值。
这样只用一遍遍历即可得出结果。
# C++
``` C++
class Solution {
public:
vector<int> countBits(int num) {
vector<int>res(num + 1, 0);
for(int i = 1; i <= num; i++)
res[i] = res[i >> 1] + (i & 1);
// res[i] = res[i & (i-1)] + 1;
return res;
}
};
```