Number of 1 Bits
Problem
Given an unsigned integer n, return the number of '1' bits it has (also known as the Hamming weight).
- The input must be treated as an unsigned integer.
- The number of bits in n can be up to 32 or 64 depending on the system.
Example
n = 113The binary representation of 11 is 1011, which contains three '1' bits. The algorithm repeatedly removes the rightmost set bit from n by performing n &= (n - 1), incrementing a counter each time until n becomes zero. This efficiently counts all set bits without checking each bit individually.
Approach
Straightforward Solution
A naive approach checks each bit individually by shifting and masking, resulting in O(k) time where k is the number of bits (e.g., 32 or 64). This is simple but not optimal.
Core Observation
Each '1' bit in the binary representation corresponds to a set bit. The operation n & (n - 1) removes the rightmost set bit from n, reducing the number of set bits by one each time it is applied.
Path to Optimal
PreviewThe key recognition signals are 'count number of set bits' and 'bitwise operations'. These indicate Bit Manipulation because the problem can be solved by exploiting properties of binary numbers…
Full step-by-step walkthrough on Pro →
Optimal Approach
PreviewUse Brian Kernighan’s algorithm: repeatedly apply n &= (n - 1) to clear the rightmost set bit and increment a counter until n becomes zero…
Full step-by-step walkthrough on Pro →
Want the full reasoning chain?
Unlock the complete walkthrough, line-by-line analysis, and recall drill.
Unlock ProTime
O(m)
Each iteration removes one set bit from n, so the loop runs exactly as many times as there are '1' bits in n.
Space
O(1)
Only a fixed number of variables are used (res and n), so the auxiliary space is constant regardless of input size.
Pattern Spotlight
Bit Manipulation (Brian Kernighan’s Algorithm for Counting Set Bits)
The operation n & (n - 1) removes the rightmost set bit, enabling a loop that runs exactly as many times as there are set bits, making counting bits efficient and elegant.
Solution
| 1 | class Solution:
|
| 2 | def hammingWeight(self, n: int) -> int:
|
| 3 | res = 0
|
| 4 | while n:
|
| 5 | n &= (n - 1)
|
| 6 | res += 1
|
| 7 | return res |
Step-by-Step Solution
Count Set Bits by Clearing Rightmost Set Bit Iteratively
| 3 | res = 0
|
| 4 | while n:
|
| 5 | n &= (n - 1)
|
| 6 | res += 1
|
| 7 | return res |
Objective
To count the number of '1' bits by repeatedly removing the rightmost set bit until the number becomes zero.
Key Insight
The operation n &= (n - 1) efficiently clears the rightmost set bit in each iteration, reducing the problem size by one set bit at a time. This avoids checking every bit individually and leads to a loop that runs only as many times as there are set bits, which is often much faster than scanning all bits.
Interview Quick-Check
Core Logic
Using n &= (n - 1) removes the rightmost set bit, so the loop executes exactly once per set bit, making the count efficient.
State & Boundaries
The loop continues while n is non-zero, ensuring all set bits are counted.
Common Pitfalls & Bugs
A common mistake is to iterate over all bits using shifts, which is less efficient when the number of set bits is small.
Complexity
The time complexity depends on the number of set bits, not the total bit length, which can be a significant optimization.
Line Analysis
This solution has 2 Critical lines interviewers watch for.
n &= (n - 1)
Remove the rightmost set bit from n using bitwise AND with n - 1.
This operation exploits binary arithmetic properties to clear the least significant '1' bit, reducing the problem size efficiently without examining each bit individually.
res += 1
Increment the counter for each removed set bit.
Each iteration corresponds to removing exactly one set bit, so incrementing the counter here accurately counts the total number of '1' bits.
Full line-by-line criticality + rationale for all 5 lines available on Pro.
Test Your Understanding
Why does the operation n &= (n - 1) remove the rightmost set bit from n?
See the answer with Pro.
Related Problems
Bit Manipulation pattern
Don't just read it. Drill it.
Reconstruct Number of 1 Bits from memory until it sticks. AlgoDrill blanks out key lines and makes you fill them back in, step by step.
Unlock the Number of 1 Bits drill