问题描述
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].
分析
a. 如果num是偶数,那么它可以由左移num的半数形成,如110(6)= 011(3)<< 1。 显然,两者中的1的数目是相同的;
b.如果num是奇数,那么它的计数就是1(小于1)的偶数1和LSB上的单个1的和,就像1101(13)= 1100(12)+ 0001(1),12可以按照a的情况形成; 1100(12)= 0110(6)<< 1;
把这两个案件放在一起:
num是偶数:ret [num] = ret [num / 2]
num是奇数:ret [num] = ret [(num -1)/ 2] + 1
所以它可以被降低为:ret [i] = ret [i / 2] + i%2
算法(C++)
vector<int> countBits(int num) {
vector<int> ret(num+1, 0);
for ( int i = 1; i <= num; i++ ) {
ret[i] = ret[i/2] + i % 2;
}
return ret;
}