Counting Bits
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:
1 public class Solution { 2 public int[] countBits(int num) { 3 int[] result = new int[num + 1]; 4 5 for (int i = 0; i <= num; i++) { 6 result[i] = countEach(i); 7 } 8 9 return result; 10 } 11 12 public int countEach(int num) { 13 int result = 0; 14 15 while (num != 0) { 16 if ((num & 1) == 1) { 17 result++; 18 } 19 num = num >>> 1; 20 } 21 22 return result; 23 } 24 }
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
.
1 public int[] countBits(int num) { 2 int[] result = new int[num + 1]; 3 4 int pow = 1; 5 for (int i = 1; i <= num; i++) { 6 if (i == pow) { 7 result[i] = 1; 8 pow = pow << 1; 9 } else { 10 int p = pow >> 1; 11 result[i] = result[p] + result[i - p]; 12 } 13 } 14 return result; 15 }