Title Link: https://leetcode.com/problems/counting-bits/
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 retur n 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:C[i]: How many 1 state transition equations are in the binary of number I:c[i]=c[i>>1]+i&1For example, the binary 111 of the number 7 only needs to calculate the number of the last and the first two digits of 1, and the number of the first two bits and 110 is the same, and 11 is the same.
Algorithm:
Public int[] countbits (int num) { int res[] = new int[num+1]; for (int i=0;i<=num;i++) { Res[i] = res[i>>1]+ (i&1); } return res; }
"Leetcode" Counting Bits