338. 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 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 using any builtin function like __builtin_popcount in C + + or in any other language
classSolution { Public: Vector<int> Countbits (intnum) {Vector<int> Count_v (num+1,0); for(inti =1; I <= num;i++) { intx =i; intCount=0; while(x) {if((X &1)==1) count++; X>>=1; } Count_v[i]=count; } returnCount_v; }};
Note: 1. Calculate the number of 1 in binary, the difficulty lies in the complexity of time. There are three basic ways to find binary 1 numbers:
- (1) theorem solving: The method of taking the remainder, the slowest.
- (2) Basic Law (FOG): Values and 1 for & operations, then >> arithmetic right shift, there are still two loops. (That is, my solution to this problem)
- (3) Fast method: N and n-1 for & operation, can eliminate the binary right 1, there are still two loops. (Solution in 191 questions)
-
Reference: http://www.cnblogs.com/graphics/archive/2010/06/21/1752421.html
Leetcode 338. Counting Bits