Problem overview
The method hammingWeight(n) receives a non-negative integer and returns how many 1 bits its binary form has. This count is also called the Hamming weight. For n = 11 the binary form is 1011, which has three 1 bits, so the answer is 3. For n = 128, which is 10000000, the answer is 1.
The statement asks for O(k) time, where k is the number of 1 bits, rather than one step per digit, and O(1) extra space.
Approach: remove the lowest 1 bit each time
The obvious method checks each of the 31 bit positions in turn. This lesson uses a faster trick that does one step per 1 bit and skips the zeros.
Look at what subtracting 1 does in binary. The lowest 1 bit becomes 0, every 0 below it becomes 1, and the bits above stay the same. For 12 (1100), 12 - 1 is 11 (1011). Now take the bitwise AND of the two: a result bit is 1 only where both numbers have a 1. Everything below the lowest 1 bit is 0 in the original, so it cancels, the lowest 1 bit itself is 0 in the other number, and the bits above are identical in both, so they stay. The result, 1000, is 12 with its lowest 1 bit removed.
So n & (n - 1) removes exactly one 1 bit. Repeat until n reaches 0 and count the repetitions. For 12 the loop runs twice: 1100 & 1011 gives 1000, then 1000 & 0111 gives 0.
Step by step
- Create
countwithlet, starting at 0. It counts the bits removed. - Loop while
n !== 0. The loop ends right after the last 1 bit is removed. - Replace
nwithn & (n - 1). This is the key line. The parentheses matter for readability: the subtraction happens first because-binds tighter than&. - Add 1 to
countinside the loop: one pass removed one bit. - Return
countafter the loop.
The solution in JavaScript
class Solution {
/**
* @param {number} n
* @return {number}
*/
hammingWeight(n) {
let count = 0;
while (n !== 0) {
n = n & (n - 1);
count++;
}
return count;
}
}
JavaScript details that matter here:
- Bitwise operators work on 32 bits. JavaScript numbers are doubles, but
&,|,^and the shifts first convert their operands to signed 32-bit integers. The lesson's range, up to 2147483647 (2**31 - 1), fits, so every bit ofnis counted correctly. - Larger values are truncated. Outside the lesson's range, the conversion keeps only the low 32 bits.
hammingWeight(4294967299)returns2, although 4294967299 (2**32 + 3) has three 1 bits, because the bit above the 32nd is lost. Don't rely on the method beyond 31 bits. - The loop condition.
n !== 0is a strict comparison to the number 0. Aftern & (n - 1),nis always an int32, so it reaches exactly 0. - Reassigning a parameter is allowed. It changes only the local copy of
n.
Complexity
Time: O(k), where k is the number of 1 bits. Each pass removes one, so there are exactly k passes, at most 31 for the values in this lesson. For 128, with a single 1 bit, the loop runs once even though the number has eight digits.
Space: O(1). Only count and the changing n are stored.
Edge cases and common mistakes
- Zero.
hammingWeight(0)returns0because the loop never runs. - All bits set.
2147483647is 31 ones in a row and returns31. The loop runs 31 times. - A single bit. Powers of two, such as 1 or 128, return
1. - Missing parentheses.
n & n - 1happens to parse the same way, because-binds tighter than&. Writing the parentheses makes the intent clear and avoids mistakes when mixing operators like+and&in other code. - Forgetting to update
n. Writingn & (n - 1)without assigning the result leavesnunchanged, and the loop never ends. - Using
==or!n. These work here, but!== 0states what you mean without type conversions.
Testing
n = 11gives3.n = 128gives1.n = 2147483645gives30.n = 0gives0.n = 7gives3.n = 12gives2.n = 2147483647gives31.
