Learning Outcome
After this lesson, you should be able to count set bits by clearing one set bit per loop.
Problem Statement
Given an integer n, return the number of 1 bits in its binary representation.
| Input | Output | Why |
|---|---|---|
n = 11 | 3 | 11 is binary 1011, which has three set bits. |
Brute Force Approach
Check every bit position one by one. This is fine for fixed width but does unnecessary work for sparse numbers.
Optimized Approach
Use Brian Kernighan's trick: n & (n
- removes the lowest set bit each time, so the number of loop iterations equals the number of 1 bits.
Exact Pseudocode
count = 0
while n != 0:
n = n & (n - 1)
count += 1
return count
Reference Code
class Solution:
def hammingWeight(self, n):
count = 0
while n:
n &= n - 1
count += 1
return countSample Dry Run
| Step | State | Result |
|---|---|---|
| n = 11 | binary 1011 | count = 0 |
| Clear bit 1 | 1011 -> 1010 | count = 1 |
| Clear bit 2 | 1010 -> 1000 | count = 2 |
| Clear bit 3 | 1000 -> 0000 | count = 3 |
Complexity
| Measure | Value | Reason |
|---|---|---|
| Time | O(number of set bits) | The loop runs once per set bit. |
| Space | O(1) | Only the count variable is stored. |
Edge Cases
- n = 0 should return 0.
- Use unsigned types in C++ when the prompt treats n as unsigned.
- A signed right shift approach can be tricky for negative values.
Interview Checklist
Use n &= n
- 1 to remove one set bit.
- Increment count once per removal.
- Stop when n becomes zero.
FAQs
Why is this faster for sparse numbers?
It skips zero bits entirely and loops only over set bits.
What does Brian Kernighan's trick clear?
It clears the lowest set bit.
What is the core pattern?
Repeated lowest-set-bit removal.