标签:
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:
class Solution { public: vector<int> countBits(int num) { vector<int> count_v(num+1,0); for(int i = 1; i <= num;i++) { int x = i; int count=0; while(x) { if((x & 1)==1) count++; x >>= 1; } count_v[i] = count; } return count_v; } };
注意:1.计算二进制中1的个数,难点在于时间复杂度。有三种基本求二进制1个数的方法:
参考:http://www.cnblogs.com/graphics/archive/2010/06/21/1752421.html
标签:
原文地址:http://www.cnblogs.com/dystopia/p/5312252.html