Number of 1 Bits
Pattern: Counting bits
n & (n - 1) clears the lowest set bit. Repeat until n is 0, counting the steps. The loop runs once per set bit.
The problem
Given a positive whole number n, return the number of 1 bits in its binary form (its Hamming weight). For example, 11
(1011) gives 3, 128 gives 1, and 2147483645 gives 30.
The function name hammingWeight matches LeetCode. Use the link above for the exact statement and limits. This guide's
tests use values from 0 to 2³¹ - 1.
Think first
- How would you check each of the 32 bits?
- What does
n & (n - 1)remove? - Can the loop run fewer than 32 times?
Hints
Brute force, and why it fails
Check all 32 bits: always 32 steps. Clearing the lowest set bit takes as many steps as there are ones. Most languages also have a built-in popcount.
The key insight
Clearing the lowest set bit jumps straight from one 1 to the next, skipping all the zeros in between.
Dry run
| n | 1011 |
|---|---|
| count | 0 |
n = 11, which is 1011 in binary.
The plan
count = 0
while n != 0: n = n & (n - 1); count = count + 1
return count
Complexity
- Time
O(number of set bits)- Space
O(1)
At most 32 steps.
Edge cases
- 0: 0.
- A power of two: 1.
- 2³¹ - 1: 31.
I've built my logic, show the code
Java
class Solution {
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
n &= n - 1; // each step clears exactly one set bit
count++;
}
return count;
}
}C++
class Solution {
public:
int hammingWeight(int n) {
unsigned int x = static_cast<unsigned int>(n);
int count = 0;
while (x != 0) {
x &= x - 1; // each step clears exactly one set bit
count++;
}
return count;
}
};Python
class Solution:
def hammingWeight(self, n: int) -> int:
count = 0
while n:
n &= n - 1 # each step clears exactly one set bit
count += 1
return countCommon mistakes
- Looping
while n > 0on a value that may be negative in Java or C++. - Using
>>on negative numbers in Java, which keeps the sign bit; use>>>for an unsigned shift. - Converting to a string, which works but is slower and uses memory.