Idea 1:
1. Determine whether each bit is 1 by shifting
2. Iterate over all numbers
class Solution { public int[] countBits(int num) { int[] res=new int[num+1]; for(int i=0;i<=num;i++){ res[i]=binaryToDecimal(i); } return res; } public int binaryToDecimal(int n){ int res=0; for(int i = 31;i >= 0; i--){ if((n>>>i & 1)==1){ res++; } } return res; } }
Idea 2:
I haven't understood it yet, but the space complexity is lower than the above one
public int[] countBits(int num) { int [] f = new int [num + 1]; for (int i=1; i<=num; i++) f[i] = f[i >> 1] + (i & 1); return f; }