leetcode-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]
.
计算比特位的1的个数,利用位运算来解决
vector<int> countBits(int num) { vector <int> ret; for (int i = 0; i <= num; i++) { int x = i, count = 0; while (x) { if (x & 1) { count++; } x >>= 1; } ret.push_back(count); } return ret; }