Tianhe Gao

LC 383. Counting Bits

 1/**
 2 * @param {number} n
 3 * @return {number[]}
 4 */
 5var countBits = function (n) {
 6  const bits = new Array(n + 1).fill(0)
 7  for (let i = 0; i <= n; i++) {
 8    bits[i] = countOnes(i)
 9  }
10  return bits
11};
12const countOnes = (x) => {
13  let ones = 0
14  while (x > 0) {
15    x &= (x - 1)
16    ones++
17  }
18  return ones
19}

No notes link to this note

Welcome to tell me your thoughts via "email"
UP