Count the Bits

Write the code, see it run, pass the checks.

The problem

  • easy
  • Code

Write countBits(n): return an array of n + 1 numbers where the number at index i is how many 1 bits there are in i written in binary, for every i from 0 to n. n is a whole number from 0 to 1,000,000. For example, countBits(5) is [0, 1, 1, 2, 1, 2], because 0 to 5 in binary are 0, 1, 10, 11, 100 and 101. Try to reuse the counts you've already worked out: i has the same 1 bits as i with its last bit dropped, plus that last bit.

Your code must pass

  • Counts the bits from 0 to n
  • Returns [0] when n is 0
  • Returns n + 1 counts
  • Counts the bits of bigger numbers