LC 383. Counting Bits
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
| /**
* @param {number} n
* @return {number[]}
*/
var countBits = function (n) {
const bits = new Array(n + 1).fill(0)
for (let i = 0; i <= n; i++) {
bits[i] = countOnes(i)
}
return bits
};
const countOnes = (x) => {
let ones = 0
while (x > 0) {
x &= (x - 1)
ones++
}
return ones
}
|
评论和交流请发送邮件到 me@tianhegao.com