338. Counting Bits
Description:
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.
Solution:
一、题意理解
给一个非负整数num,返回一个数组,数组中第i项(0 ≤ i ≤ num)是数字i的二进制表示串的1的数量。
例如,给定数字num = 5,从0~5的二进制表示及1的数量为:
0 0000 0
1 0001 1
2 0010 1
3 0011 2
4 0100 1
5 0101 2
所以,返回结果数组为[0, 1, 1, 2, 1, 2]。
二、分析
1、朴素法就是从0到num进行循环,依次对每个数进行移位操作,计算二进制串1的数量,时间复杂度为O(n*sizeof(integer))。
2、但我们可以寻找一种前后对应关系,即某两个数在二进制表示上是否有相关的关系。类似斐波那契数列,找到一种状态转移方程。即设F(a)为整数a的二进制串1的数量,G( F(a) )是某一种运算,使得F(b) = G(F(a)),其中b是和a有某种关系的另一个整数。
3、幸运地是,我们可以找到这样的两个数,有F(b) = F(a) + 1,其中,a <b 且满足a = b&(b-1)。那为什么当a和b满足 a = b&(b-1)时,就有F(b) = F(a) + 1呢?很简单,b&(b-1)的意义是清除b的最后一个set位(set位是指二进制串中1的位置)。举个例子如下
b 12 1100 2
b-1 11 1011 3
a = b&(b-1) 8 1000 1
这样,既然b清除了最后一个set位得到a,那么b的1的数量自然就比a的多一个。
4、得出状态转移方程,我们就很容易能写出代码如下:
class Solution {
public:
vector<int> countBits(int num) {
vector<int> ret(num+1, 0);
for (int i = 1; i <= num; ++i)
ret[i] = ret[i&(i-1)] + 1;
return ret;
}
};
5、时间复杂度为O(n),空间复杂度O(n)。