Count set bits (Hamming weight)

Easy TimeO(log n) SpaceO(1)Bit manipulation

Every whole number has a binary form: 29 is 11101. Given a number n, zero or greater, return how many 1s appear in it. Zero has none at all, and leading zeros are not bits so they never add to the count.

Examples

Example 1

Input
n = 29
Output
4
29 is 11101, which holds four 1s and one 0.

Example 2

Input
n = 0
Output
0
Zero has no 1s anywhere, so the count is 0.

The Code

JScountSetBits.js
1function countSetBits(n) {2  let count = 0;3  while (n > 0) {4    count += n & 1;5    n = n >>> 1;6  }7  return count;8}9countSetBits(29);
Done
Step through countSetBits(29) call by call