Problem overview
The function hamming_weight receives a non-negative i32, n, and returns how many 1 bits its binary form has. This count is also called the Hamming weight, or population count.
For n = 11, the binary form is 1011, so the answer is 3. For n = 128, which is 10000000, the answer is 1. For n = 2147483645, the binary form has thirty-one digits, all 1 except a single 0 just before the last digit, so the answer is 30.
Approach: remove one 1 bit per loop pass
The obvious method looks at all 31 or 32 bit positions and tests each one. That always costs the same number of steps, even for 128, which has a single 1. The lesson asks for O(k) time, where k is the number of 1 bits, so the loop has to run once per 1 bit and skip the 0s.
The trick rests on what subtracting 1 does in binary. The lowest 1 bit of n becomes 0, every 0 below it becomes 1, and the bits above it stay the same. For 12 and 11:
1100 & 1011 = 1000
1000 & 0111 = 0000
The AND of n and n - 1 keeps the bits that both numbers share. Below the lowest 1 bit, n has only 0s, so nothing survives there. At that bit, n has a 1 and n - 1 has a 0, so it disappears. Above it, the two numbers agree. Net effect: n & (n - 1) is n with its lowest 1 bit cleared. Repeat until the number is 0 and count the repetitions.
Step by step
- Copy
nintonum. A Rust parameter is immutable unless it is declaredmut, and the loop changes the value, so the work happens on a mutable copy. - Start
countat 0. Rust infersi32for it, because the function returns it as ani32. - Loop while
num != 0. When the last 1 bit is cleared, the number is 0 and the loop ends. A number with no 1 bits never enters the loop. - Clear the lowest 1 bit with
num = num & (num - 1). - Add 1 to
count. Each pass removed exactly one 1 bit. - Return
countas the last expression, without a semicolon.
The solution in Rust
impl Solution {
fn hamming_weight(n: i32) -> i32 {
let mut num = n;
let mut count = 0;
while num != 0 {
num = num & (num - 1);
count += 1;
}
count
}
}
Rust details worth knowing:
&is two operators. Innum & (num - 1)it is bitwise AND, because it sits between two values. In front of a single value, as in&edges, it creates a reference.- The subtraction is safe here. The loop only runs while
numis not 0, and the inputs are non-negative, sonum - 1never goes below 0. - Standard library. Integer types have a method for this,
n.count_ones(), which returns au32. The loop is the lesson's exercise; in everyday code the method is the shorter choice.
Complexity
Time: O(k). Every pass removes one 1 bit, so the loop runs exactly k times. For these inputs k is at most 31. Checking every bit position would take 31 steps whatever the input.
Space: O(1). The function keeps two integers.
Edge cases and common mistakes
- Zero.
n = 0skips the loop and returns 0. - A single bit. A power of two such as 128 takes one pass and returns 1.
- All ones.
n = 2147483647takes 31 passes and returns 31. - Operator precedence. In Rust, subtraction binds tighter than
&, sonum & num - 1means the same asnum & (num - 1). The parentheses are optional, but they make the intent clear to the reader. - Forgetting
mut. Assigning to the parameterndirectly is a compile error, which is why the solution copies it first. - Using
num - 1instead of AND. Subtracting alone changes the value but doesn't clear a bit, and the loop would count the wrong thing.
Testing
n = 11gives3.n = 128gives1.n = 2147483645gives30.n = 0gives0.n = 2147483647gives31.
