Topic:
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 you num = 5 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 I do it in linear time O (n)/possibly in a single pass?
- Space complexity should be O (n).
- Can do it like a boss? Do it without the using any builtin function like __builtin_popcount in C + + or any other language.
Ideas:
1. Check what each bit is, which is what it says very simple idea
2. Even words, is 1 of the previous number of digits + 1, even words/2 until it is odd, because the two cups relative to the shift, 1 of the same number of digits
Code: C + + idea 2:
classSolution { Public: Vector<int> Countbits (intnum) {Vector<int>solve; if(Num <0) returnsolve; Solve.push_back (0); if(num = =0){ returnsolve; } for(inti =1; I <= num;i++){ intindex =i; ifI2){//i is an odd numberSolve.push_back (Solve.back () +1); } Else{ while(index%2==0) Index/=2; Solve.push_back (Solve[index]); } } returnsolve; }};
Leetcode 338. Counting Bits