counting bits
Think in terms of odd and even numbers
if number is even the number of 1s will be same as that in number/2
if number is odd the number of 1s will be number of 1’s in (number/2) + 1
public class Solution {
public int[] countBits(int num) {
int[] ans = new int[num + 1];
for (int i = 1; i <= num; ++i)
ans[i] = ans[i >> 1] + (i & 1); // x / 2 is x >> 1 and x % 2 is x & 1
return ans;
}
}