Start learning free

LESSON 304 OF 314 · BIT MANIPULATION

Number of 1 Bits in Rust: Clearing the Lowest Set Bit

Practice O(k) Read the full explanation

Given a non-negative integer n, return the number of 1 bits in its binary representation (also called its Hamming weight).

 

Example 1:

Input: n = 11
Output: 3
Explanation: 11 in binary is 1011, which has three 1 bits.

Example 2:

Input: n = 128
Output: 1
Explanation: 128 in binary is 10000000, which has a single 1 bit.

Example 3:

Input: n = 2147483645
Output: 30
Explanation: 2147483645 in binary is 1111111111111111111111111111101: thirty-one digits, and all but one of them are 1.

 

Constraints:

  • 0 <= n <= 231 - 1
Note:

Your algorithm should run in O(k) time, where k is the number of 1 bits in n, and use O(1) extra space.



Look at what subtracting 1 does to a number in binary: its lowest 1 bit turns into 0, every 0 below it turns into 1, and the higher bits stay the same. For example, 12 is 1100 and 11 is 1011.

So n AND n - 1 is n with its lowest 1 bit removed: 1100 AND 1011 is 1000. Keep doing it until n becomes 0, and count how many times you did it.

Each pass of the loop removes one 1 bit, so the loop runs k times, at most 31 for these values: O(k) time.
We keep only the count and the number we change, so the extra space is O(1).
STEP 1 OF 6
    Ctrl + Enter to check

    RUST · BIT MANIPULATION

    Number Of 1 Bits in Rust, explained

    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

    1. Copy n into num. A Rust parameter is immutable unless it is declared mut, and the loop changes the value, so the work happens on a mutable copy.
    2. Start count at 0. Rust infers i32 for it, because the function returns it as an i32.
    3. 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.
    4. Clear the lowest 1 bit with num = num & (num - 1).
    5. Add 1 to count. Each pass removed exactly one 1 bit.
    6. Return count as 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. In num & (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 num is not 0, and the inputs are non-negative, so num - 1 never goes below 0.
    • Standard library. Integer types have a method for this, n.count_ones(), which returns a u32. 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 = 0 skips the loop and returns 0.
    • A single bit. A power of two such as 128 takes one pass and returns 1.
    • All ones. n = 2147483647 takes 31 passes and returns 31.
    • Operator precedence. In Rust, subtraction binds tighter than &, so num & num - 1 means the same as num & (num - 1). The parentheses are optional, but they make the intent clear to the reader.
    • Forgetting mut. Assigning to the parameter n directly is a compile error, which is why the solution copies it first.
    • Using num - 1 instead of AND. Subtracting alone changes the value but doesn't clear a bit, and the loop would count the wrong thing.

    Testing

    • n = 11 gives 3.
    • n = 128 gives 1.
    • n = 2147483645 gives 30.
    • n = 0 gives 0.
    • n = 2147483647 gives 31.
    Keep going with Rust1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free