Problem: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]
.
Follow up:
- It is very easy to come up with a solution with run time O(n*sizeof(integer)). But can you do it in linear time O(n) /possibly in a single pass?
- Space complexity should be O(n).
- Can you do it like a boss? Do it without using any builtin function like __builtin_popcount in c++ or in any other language.
Question: Given a non-negative integer n, calculate the number of 1 bits in each binary number in the [0,n] interval.
Requirements: Time complexity is optimized to O(n), space complexity is O(n) , and built-in functions are not used.
Idea: List the 0-16 sample cases. When i is a power of 2, 1bit is 1. When it is not a power, it is equivalent to adding 1 to the number after subtracting the last encountered number that is a power;
Code:
class Solution {
public int[] countBits(int num) {
int[] ret = new int[num + 1];
if (num == 0)
return ret;
ret[0] = 0;
int flag = 0;
for (int i = 1; i <= num; i++) {
if ((i & (i - 1)) == 0) {
flag = i;
ret[i] = 1;
} else {
ret[i] = ret[i - flag] + 1;
}
}
return ret;
}
}
Submit the result:
Look at the best optimized solution using right shift. I have thought of the idea, but I am not sure. At that time, I just thought about how to remove the highest bit 1. . .
Code:
class Solution {
//338. Counting Bits
public int[] countBits(int num) {
int[] ret = new int[num + 1];
for(int i=0;i<=num;i++) {
ret[i]=ret[i>>1]+(i&1);
}
return ret;
}
}