Counting Bitsc++
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.ui
Example:
For num = 5
you should return [0,1,1,2,1,2]
.this
Follow up:spa
Show Hint code
Credits:
Special thanks to @ syedee for adding this problem and creating all test cases.blog
解法一:ci
按照定義作,注意,x&(x-1)能夠消去最右邊的1leetcode
class Solution { public: vector<int> countBits(int num) { vector<int> ret; for(int i = 0; i <= num; i ++) ret.push_back(countbit(i)); return ret; } int countbit(int i) { int count = 0; while(i) { i &= (i-1); count ++; } return count; } };
解法二:get
對於[2^k, 2^(k+1)-1]區間,能夠劃分紅先後兩部分it
前半部分與[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(0); if(num == 0) // start case 1 return ret; ret.push_back(1); if(num == 1) // start case 2 return ret; // general case else { int k = 0; int result = 1; while(result-1 < num) { result *= 2; k ++; } // to here, num∈ [2^(k-1),2^k-1] int gap = pow(2.0, k) - 1 - num; for(int i = 0; i < k-2; 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+1)-1; j ++) ret.push_back(ret[j]); // plus 1 part for(int j = pow(2.0, i); j <= pow(2.0, i+1)-1; j ++) ret.push_back(ret[j]+1); } for(int i = 0; i < pow(2.0, k-1) - gap; i ++) { int j = pow(2.0, k-2) + i; if(i < pow(2.0, k-2)) // copy part ret.push_back(ret[j]); else // plus 1 part ret.push_back(ret[j]+1); } } return ret; } };