Problem overview
The method hammingWeight takes a non-negative int n and returns how many 1 bits its binary form has. For n = 11, which is 1011, the answer is 3. For n = 128, which is 10000000, it is 1. For n = 2147483645, whose 31 binary digits are all 1 except one, it is 30.
The statement asks for O(k) time, where k is the number of 1 bits, and O(1) extra space.
Approach: remove the lowest 1 bit each time
The obvious way tests every bit position, one pass for each of the 31 or 32 bits. That takes the same time whether the number has one 1 bit or thirty. The lesson uses a trick that does one pass per 1 bit.
Subtracting 1 from a number turns its lowest 1 bit into 0 and every 0 below that bit into 1; higher bits stay as they are. So n & (n - 1) keeps the higher bits and clears the lowest 1 bit and everything below it, which was already 0. In short, it removes exactly one 1 bit. Repeating this until n is 0 takes k rounds, and counting the rounds gives the answer.
For n = 11, the rounds produce 1010 (10), then 1000 (8), then 0. That is three rounds, so the answer is 3. Running the lesson's code on that value, n takes the values 10, 8 and 0 in turn.
Step by step
- Create
countand start it at 0. - Loop while
n != 0. When the last 1 bit has been removed,nis 0 and the loop ends. - Clear the lowest 1 bit with
n = n & (n - 1). - Increase
count: one bit was removed. - Return
count.
The solution in C++
class Solution {
public:
int hammingWeight(int n) {
int count = 0;
while (n != 0) {
n = n & (n - 1);
count++;
}
return count;
}
};
C++ details worth knowing:
- Precedence.
&binds more loosely than+,-and even==. Heren & n - 1would mean the same thing, but the parentheses make it readable, and in an expression likei & 1 + 1the addition happens first: withi = 3it gives 2, not 1. nis a copy. The parameter is passed by value, so the loop can change it freely without touching the caller's number.- Why the input range matters. The constraints keep
nbetween 0 and 2,147,483,647, so it is never negative andn - 1never underflows theint. Forn = 0the loop doesn't run and the result is 0.
Complexity
Time: O(k). Each pass removes one 1 bit, so the loop runs exactly k times, at most 31 for these inputs.
Space: O(1). Only count and the changing copy of n are kept.
Edge cases and common mistakes
- Zero.
n = 0has no 1 bits; the loop is skipped and 0 is returned. - Powers of two.
128has one 1 bit, so the loop runs once:128 & 127is 0. - The largest input.
n = 2147483647has 31 bits, all 1, and the answer is 31. - Using
&&instead of&.&&is the logical AND, which gives 0 or 1, not a bit-by-bit result. - Forgetting to assign. Writing
n & (n - 1);alone computes a value and throws it away, so the loop never ends.
Testing
n = 11gives 3.n = 128gives 1.n = 2147483645gives 30.n = 0gives 0.n = 12gives 2.n = 2147483647gives 31.
