Count set bits (Hamming weight)
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
- 29 is
411101, which holds four 1s and one 0.
Example 2
- Input
- n = 0
- Output
- Zero has no 1s anywhere, so the count is
00.
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