Counting Bits LeetCode solution in JavaScript

1
var countBits = function (n) {
2
if (n === 0) return [0];
3

4
const ans = new Array(n + 1).fill(0);
5

6
let currRoot = 0;
7
for (let idx = 1; idx <= n; idx++) {
8
if ((idx & (idx - 1)) === 0) {
9
ans[idx] = 1;
10
currRoot = idx;
11
continue;
12
}
13

14
ans[idx] = 1 + ans[idx - currRoot];
15
}
16

17
return ans;
18
};

0

WPM •0 •0

100%

ACC •0 •0

0s

TIME •0