【LeetCode】338. 比特位计数

338. 比特位计数

思路

  1. 位运算

拓展

  1. __builtin_popcount的使用
    1178. 猜字谜

代码

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
class Solution {
public:
vector<int> countBits(int num) {

vector<int> ans;
for(int i=0;i<=num;i++)
{
int cnt=0;
int temp=i;
while(temp>0)
{
temp&=(temp-1);
cnt++;
}
ans.push_back(cnt);
}
return ans;
}
};