multiplex
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| class Solution { public int[] countBits(int n) {
int[] array = new int[n + 1]; int nthPower = 1, i = nthPower; while (true) { int upperBound = nthPower * 2; while (i < array.length && i < upperBound) { array[i] = 1 + array[i - nthPower]; i++; }
if (i == array.length) { break; }
nthPower = upperBound; }
return array; } }
|
odd-even
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
| class Solution { public int[] countBits(int n) { int[] res = new int[n + 1]; for (int i = 1; i <= n; i++) { if ((i & 1) == 1) { res[i] = res[i - 1] + 1; } else { res[i] = res[i >> 1]; } } return res; } }
|
References
338. Counting Bits
剑指 Offer II 003. 前 n 个数字二进制中 1 的个数