看了提示写出来的
const countBits = function (num) {
let res = [], count = 0, str = '';
for (let i = 0; i <= num; ++i) {
let n = i;
while (n !== 0) {
if (res[n]) {
count += res[n];
break;
}
if (n % 2 === 1) {
++count;
}
n = parseInt(n / 2);
}
res[i] = count;
count = 0;
}
return res;
};
评论区很棒的解法 f[8] = f[4] + 8的最后一位是不是1,因为移位会把最后一位挤出去,所以要判断下最后一位;
const countBits = function (num) {
let f = [0], count = 0, str = '';
for (let i=1; i<=num; i++) f[i] = f[i >> 1] + (i & 1);
return f;
};