Given a non-negative integer num. For 0 ≤ i ≤ i, each digital num range, which calculates the number of binary digits 1 and returns them as an array.
Example 1:
Input: 2
Output: [0,1,1]
Example 2:
Input: 5
Output: [0,1,1,2,1,2]
Solution 1: use the library functions
class Solution {
public int[] countBits(int num) {
int[] arr = new int[num + 1];
for(int i = 0; i <= num; i++){
arr[i] = Integer.bitCount(i);
}
return arr;
}
}
Solution two:
class Solution {
public int[] countBits(int num) {
int[] arr = new int[num + 1];
for(int i = 1; i <= num; i++){
arr[i] = arr[(i & i- 1)] + 1;
}
return arr;
}
}