Question:
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.
Analysis:
Given a nonnegative integer, num, for each I of 0≤i≤num, calculates how many of the bits in I are 1, and returns an array of the number of records 1.
Follow up:
Can you just walk through the time in O (n) to get an answer?
The spatial complexity is O (n).
Ideas:
Because the number of 1 is calculated, it must be related to the remainder after 2 and 2. The calculation is incremented, so the next number can take advantage of the result of the previous number.
The code is as follows:
Public classSolution { Public int[] Countbits (intnum) { int[] DP =New int[Num+1]; dp[0] = 0; for(intI=1; i<=num; i++) { intT1 = I/2; intt2 = i% 2; Dp[i]= Dp[t1] +T2; } returnDP; }}
Leetcode--Counting Bits