leetcode-338 Counting Bits

338. Counting Bits

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.

Example 1:

1
2
Input: 2
Output: [0,1,1]

Example 2:

1
2
Input: 5
Output: [0,1,1,2,1,2]

Follow up:

  • It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
  • Space complexity should be O(n).
  • Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.

Analyse

给定一个非负整数num,计算[0, num]范围内所有数的二进制表示中 1 的个数,以数组的形式输出

先解决怎么数二进制中的 1 的问题,二进制的 1 除了最后一位,都代表 2 的幂次,
比如 7 的二进制111中的 1 分别代表,$2^2$, $2^1$,$2^0$,

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
int CountBit(int num)
{
int count = 0;
while (num != 0)
{
if (num % 2 == 1)
{
count++;
}
num = num >> 1;
}
return count;
}

vector<int> countBits(int num)
{
vector<int> vec;
for(int i = 0; i <= num; i++)
{
vec.push_back(CountBit(i));
}
return vec;
}