Given a non negative integer number num. For every numbersiin the range 0 ≤ i ≤ num calculate the number of 1's in their binary representation and return them as an array.
直接的做法
class Solution {
public int[] countBits(int num) {
int[] res = new int[num + 1];
int n = 0;
int upper = 1;
for(int i = 0; i <= num; i++) {
res[i] = count(i);
}
return res;
}
public int count(int n) {
int count = 0;
for(int i = 0; i < 32; i++) {
if(((n >> i) & 1) == 1)
count++;
}
return count;
}
}
DP
public class Solution {
public int[] countBits(int num) {
int[] ans = new int[num + 1];
int i = 0, b = 1;
// [0, b) is calculated
while (b <= num) {
// generate [b, 2b) or [b, num) from [0, b)
while(i < b && i + b <= num){
ans[i + b] = ans[i] + 1;
++i;
}
i = 0; // reset i
b <<= 1; // b = 2b
}
return ans;
}
}