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.
Hint:
- You should make use of what you have produced already.
- Divide the numbers in ranges like [2-3], [4-7], [8-15] and so on. And try to generate new range from previous.
- Or does the odd/even status of the number help you in calculating the number of 1s?
Hide Tags
Dynamic Programming Bit Manipulation
Hide Similar Problems
public class Solution { public int[] countBits(int num) { int[] ret = new int[num+1]; // f(i) = f(i/2) + i%2. for(int i = 1; i<=num; ++i) ret[i] = ret[i/2]+i%2; return ret; } }
191. Number of 1 Bits
Write a function that takes an unsigned integer and returns the number of ’1‘ bits it has (also known as the Hamming weight).
For example, the 32-bit integer ’11‘ has binary representation 00000000000000000000000000001011
, so the function should return 3.
Hide Tags
Hide Similar Problems
(E) Reverse Bits (E) Power of Two (M) Counting Bits
The signed right shift operator ">>
" shifts a bit pattern to the right.
The unsigned right shift operator ">>>
" shifts a zero into the leftmost position, while the leftmost position after ">>"
depends on sign extension.
e.g.
System.out.println(-1 >> 1); //-1System.out.println(-1 >> 31); //-1System.out.println(-1 >>> 29); //7System.out.println(-1 >>> 30); //3System.out.println(-1 >>> 31); //1System.out.println(-1 >>> 32); //-1, <=> -1 >>> 0System.out.println(-1 >>> 33); //2147483647, <=> -1 >>> 1
int n = -15;System.out.println(Integer.toBinaryString(n));//11111111111111111111111111110001int m = n >> 1;System.out.println(m);//-8System.out.println(n / 2);//-7System.out.println(Integer.toBinaryString(m));//11111111111111111111111111111000
Bit Operators:
http://stackoverflow.com/questions/15457893/java-right-shift-on-negative-number
https://docs.oracle.com/javase/tutorial/java/nutsandbolts/op3.html
public class Solution { // you need to treat n as an unsigned value public int hammingWeight(int n) { int sum = 0; while(n!=0) { sum += n&1; n = n >>> 1; } return sum; } }