Number of 1 Bits

EasyBit manipulation

Given an unsigned 32-bit integer n, return how many of its 32 bits are 1.

JavaScript has no unsigned 32-bit type, so the page passes n as an ordinary number from 0 to 4294967295 (2³² − 1). The bitwise operators treat numbers as signed 32-bit: >> copies the sign bit in from the left, while >>> shifts in zeros.

Examples

Example 1
Input:  n = 13
Output: 3

13 is 1101 in binary: three 1 bits.

Example 2
Input:  n = 4294967295
Output: 32

2³² − 1 has all thirty-two bits set.

Constraints

  • 0 ≤ n ≤ 4294967295
  • n is a whole number.

Stuck?

Hint 1

Look at the lowest bit with n & 1, then shift the next bit down. Pick the shift that does not drag the sign bit along.

Hint 2

A neater trick: n & (n - 1) clears the lowest 1 bit, so count how many times you can do that before n reaches 0.

Still stuck? Read the solution

JavaScript
Loading the editor

Run checks your code against the 2 examples. Submit checks all 11 tests, most of them hidden.

Ctrl + Enter runs, and adding Shift submits. On a Mac, use ⌘.

blur