【LeetCode】338. Counting Bits (2 solutions)

时间:2023-03-10 00:48:28
【LeetCode】338. Counting Bits (2 solutions)

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:
For num = 5 you should return [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.

Show Hint

Credits:
Special thanks to @ syedeefor adding this problem and creating all test cases.

解法一:

按照定义做,注意,x&(x-1)可以消去最右边的1

class Solution {
public:
vector<int> countBits(int num) {
vector<int> ret;
for(int i = ; i <= num; i ++)
ret.push_back(countbit(i));
return ret;
}
int countbit(int i)
{
int count = ;
while(i)
{
i &= (i-);
count ++;
}
return count;
}
};

【LeetCode】338. Counting Bits (2 solutions)

解法二:

对于[2^k, 2^(k+1)-1]区间,可以划分成前后两部分

前半部分与[2^(k-1), 2^k-1]内的值相同,后半部分与[2^(k-1), 2^k-1]内值+1相同。

class Solution {
public:
vector<int> countBits(int num) {
vector<int> ret; ret.push_back();
if(num == )
// start case 1
return ret;
ret.push_back(); if(num == )
// start case 2
return ret; // general case
else
{
int k = ;
int result = ;
while(result- < num)
{
result *= ;
k ++;
}
// to here, num∈ [2^(k-1),2^k-1]
int gap = pow(2.0, k) - - num;
for(int i = ; i < k-; i ++)
{// infer from [2^i, 2^(i+1)-1] to [2^(i+1), 2^(i+2)-1]
// copy part
for(int j = pow(2.0, i); j <= pow(2.0, i+)-; j ++)
ret.push_back(ret[j]);
// plus 1 part
for(int j = pow(2.0, i); j <= pow(2.0, i+)-; j ++)
ret.push_back(ret[j]+);
}
for(int i = ; i < pow(2.0, k-) - gap; i ++)
{
int j = pow(2.0, k-) + i;
if(i < pow(2.0, k-))
// copy part
ret.push_back(ret[j]);
else
// plus 1 part
ret.push_back(ret[j]+);
}
}
return ret;
}
};

【LeetCode】338. Counting Bits (2 solutions)