Count Set Bits in a Binary NumberLoading saved progress…

Count Set Bits in a Binary Number

Implement countOnesInBinary(n) — given a non-negative integer, return how many 1 bits appear in its binary representation. The number 13 is 1101 in binary, so it has three 1 bits and the answer is 3. This count goes by several names you'll see in the wild: the Hamming weight, the population count (or popcount), and the number of set bits. A set bit just means a bit position holding a 1 rather than a 0.

Signature

// n:       a non-negative integer (0, 1, 2, ...).
// returns: the number of 1 bits in n's binary form, as a number.
function countOnesInBinary(n: number): number;

Examples

countOnesInBinary(0); // → 0   (binary 0, no 1 bits)
countOnesInBinary(7); // → 3   (binary 111, three 1 bits)
countOnesInBinary(8);   // → 1   (binary 1000, one 1 bit)
countOnesInBinary(255); // → 8   (binary 11111111, eight 1 bits)

Notes

  • n is a non-negative integer. You don't need to handle negative numbers or non-integers.
  • 0 has zero set bits. The smallest input returns 0 — make sure your loop handles it without entering the body.
  • A power of two has exactly one set bit. 1, 2, 4, 8, 16 each return 1; only the position of the single bit changes.
  • Count the 1 bits, not the bit length. 8 is four bits wide (1000) but only one of them is set, so the answer is 1, not 4.
Loading editor…