LC 191 — Problem

Write a function that takes the binary representation of a positive integer and returns the number of set bits it has (also known as the Hamming weight).

Input: n = 11 (binary: 1011)
Output: 3
Explanation: The input has three set bits: positions 0, 1, and 3.
Input: n = 128 (binary: 10000000)
Output: 1

Constraints: 1 ≤ n ≤ 2³¹ - 1

Counting set bits sounds simple: check each of 32 bit positions one by one. But how much of that work is actually useful?

Tap each bit position below to “check” it. You're playing the role of the naive for (i = 0; i < 32; i++) loop — but on just 8 bits of n = 22 (binary 00010110). Notice how many checks find nothing.

FIG. 1 — N = 22 — TAP EACH BIT TO CHECK IT
?
7
?
6
?
5
?
4
?
3
?
2
?
1
?
0
— 0 of 8 checked —