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]
.
Follow up:
Hint:
i 二进制表示 '1' res[i]
0 0000 0 res[0]=0 ------------- 1 0001 1 res[1]=res[0]+1 ------------- 2 0010 1 res[2]=res[0]+1 3 0011 2 res[3]=res[1]+1 ------------- 4 0100 1 res[4]=res[0]+1 5 0101 2 res[5]=res[1]+1 6 0110 2 res[6]=res[2]+1 7 0111 3 res[7]=res[3]+1 ------------- 8 1000 1 ... 9 1001 2 10 1010 2 11 1011 3 12 1100 2 13 1101 3 14 1110 3 15 1111 4
public int[] countBits(int num) { int[] res = new int[num + 1]; int i = 1, j, k = 2; res[0] = 0; while (i <= num) { for (j = 0; i <= num && i < k; ) res[i++] = res[j++] + 1; k <<= 1; } return res; }
i 二进制表示 '1' res[i]
0 0000 0 res[0]=0 ------------- 1 0001 1 res[1]=res[0]+1 ------------- 2 0010 1 res[2]=res[1] 3 0011 2 res[3]=res[1]+1 ------------- 4 0100 1 res[4]=res[2] 5 0101 2 res[5]=res[2]+1 6 0110 2 res[6]=res[3] 7 0111 3 res[7]=res[3]+1 ------------- 8 1000 1 ... 9 1001 2 10 1010 2 11 1011 3 12 1100 2 13 1101 3 14 1110 3 15 1111 4
public int[] countBits(int num) { int[] res = new int[num + 1]; int i = 1, j, k = 2; res[0] = 0; while (i <= num) { if (i % 2 == 1) res[i] = res[i / 2] + 1; else res[i] = res[i / 2]; i++; } return res; }
i 二进制表示 '1' i&(i-1) res[i]
0 0000 0 \ res[0]=0 ------------- 1 0001 1 0 res[1]=res[0]+1 ------------- 2 0010 1 0 res[2]=res[0]+1 3 0011 2 2 res[3]=res[2]+1 ------------- 4 0100 1 0 res[4]=res[0]+1 5 0101 2 4 res[5]=res[4]+1 6 0110 2 4 res[6]=res[4]+1 7 0111 3 6 res[7]=res[6]+1 ------------- 8 1000 1 ... ... 9 1001 2 10 1010 2 11 1011 3 12 1100 2 13 1101 3 14 1110 3 15 1111 4
public int[] countBits(int num) { int[] res = new int[num + 1]; int i = 1; res[0] = 0; while (i <= num) { res[i] = res[i & (i - 1)] + 1; i++; } return res; }