Problem overview
The method hammingWeight(int n) receives a non-negative integer and returns how many 1 bits its binary form has. For n = 11, which is 1011 in binary, the answer is 3. For n = 128, which is 10000000, the answer is 1. For n = 2147483645, which is 31 binary digits with a single 0, the answer is 30.
The target is O(k) time, where k is the number of 1 bits, and O(1) extra space.
Approach: remove one 1 bit per pass
The obvious way tests all 31 or 32 bit positions one by one: check the last bit with n & 1, shift right, repeat. It works, but it always takes as many passes as there are bit positions, even for a number like 128 that has a single 1.
This lesson uses a trick that does one pass per 1 bit. The expression n & (n - 1) clears the lowest 1 bit of n. Subtracting 1 turns that lowest 1 into a 0 and turns all the 0s below it into 1s. Bits above it are unchanged. AND-ing the result with n keeps only the bits that are 1 in both, which are exactly the bits above the lowest 1.
For example, 12 is 1100 and 11 is 1011, and 12 & 11 is 1000, which is 8: 12 without its lowest 1 bit. Repeating the operation removes one 1 bit each time, so n reaches 0 after exactly as many passes as it had 1 bits. Counting the passes gives the answer.
For n = 11 the loop goes through these values:
n=10 (1010) count=1
n=8 (1000) count=2
n=0 (0) count=3
Step by step
- Create
countas anintstarting at 0. It counts the 1 bits as they are removed. - Loop while
n != 0. Each pass removes one 1 bit, sonbecomes 0 right after its last 1 bit is gone. - Clear the lowest 1 bit:
n = n & (n - 1). - Add 1 to
count, because one more 1 bit has been removed. - Return
count.
The solution in Java
class Solution {
public int hammingWeight(int n) {
int count = 0;
while (n != 0) {
n = n & (n - 1);
count++;
}
return count;
}
}
The Java details worth a closer look:
- Operator precedence. In Java,
-binds tighter than&, son & n - 1would mean the same thing. The parentheses are there for the reader. - The parameter is a copy. Assigning to
nchanges only the method's own copy, so the caller's number is untouched. n - 1never overflows here. The loop only subtracts whenn != 0and the lesson's values are non-negative, son - 1is at least 0.- Negative numbers also terminate. An
intis 32 bits and negative numbers keep their sign bit as a 1. The same loop gives 32 for-1, because every one of the 32 bits is a 1. The trick still removes one 1 bit per pass, so it ends after at most 32 passes.
Complexity
Time: O(k), where k is the number of 1 bits. Each pass removes one of them, and an int has at most 32 bits, so the loop runs at most 32 times.
Space: O(1). Only count and the parameter n are used.
Edge cases and common mistakes
- Zero. The loop never runs and the method returns 0.
- A power of two.
128 & 127is 0, so the loop runs once and returns 1. - The largest value.
2147483647has 31 bits set, so the loop runs 31 times and returns 31. - Looping
n > 0. For the lesson's non-negative values it behaves the same asn != 0, but it would stop immediately for a negative number and return 0. - Forgetting to update
n. Writingn & (n - 1)without assigning the result changes nothing, and the loop never ends. - Using
>>on a negative number. A right shift with>>copies the sign bit, so a loop likewhile (n != 0) { count += n & 1; n >>= 1; }never ends for a negativen.>>>fills with zeros instead.
Testing
n = 0gives 0.n = 11gives 3.n = 12gives 2.n = 128gives 1.n = 2147483645gives 30.n = 2147483647gives 31.
