Counting Bits

时间:2023-03-08 20:09:02

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].

From:

1. Naive Solution

We can simply count bits for each number like the following:

 public class Solution {
public int[] countBits(int num) {
int[] result = new int[num + ]; for (int i = ; i <= num; i++) {
result[i] = countEach(i);
} return result;
} public int countEach(int num) {
int result = ; while (num != ) {
if ((num & ) == ) {
result++;
}
num = num >>> ;
} return result;
}
}

2. Improved Solution

For number 2(10), 4(100), 8(1000), 16(10000), ..., the number of 1's is 1. Any other number can be converted to be 2^m + x. For example, 9=8+1, 10=8+2. The number of 1's for any other number is 1 + # of 1's in x.

Counting Bits

     public int[] countBits(int num) {
int[] result = new int[num + ]; int pow = ;
for (int i = ; i <= num; i++) {
if (i == pow) {
result[i] = ;
pow = pow << ;
} else {
int p = pow >> ;
result[i] = result[p] + result[i - p];
}
}
return result;
}