Start learning free

LESSON 304 OF 314 · BIT MANIPULATION

Number of 1 Bits in Go: 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 5
    Ctrl + Enter to check

    GO · BIT MANIPULATION

    Number Of 1 Bits in Go, explained

    Problem overview

    The function hammingWeight receives a non-negative integer n 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, so the answer is 3. For n = 128, which is 10000000, the answer is 1. For n = 2147483645, which is thirty-one binary digits with a single 0, the answer is 30.

    The lesson asks for 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 is to look at all the bits: test the last bit with n & 1, shift right, and repeat until n is 0. That does one pass per binary digit, including the 0s. The lesson uses a faster trick that does one pass per 1 bit.

    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 example, 12 is 1100 and 11 is 1011. Now AND the two numbers: the changed low part cancels out (a 1 meets a 0 everywhere), and the high part is kept. So n & (n - 1) is n with its lowest 1 bit removed: 1100 & 1011 is 1000.

    Repeat that until n is 0 and count the repetitions. Each repetition removes exactly one 1 bit, so the count is the number of 1 bits.

    Here is n = 11 printed after each pass of the loop, in binary:

    1011
    1010
    1000
    

    The first line is n before the loop starts. After three passes n is 0, and three is the answer.

    Step by step

    1. Create count with := and start it at 0.
    2. Write the loop. Go has no while, but a for with only a condition does the same job: for n != 0.
    3. Remove the lowest 1 bit with n = n & (n - 1).
    4. Add 1 to count with count++. One pass removed one bit.
    5. Return count after the loop.

    The solution in Go

    func hammingWeight(n int) int {
        count := 0
        for n != 0 {
            n = n & (n - 1)
            count++
        }
        return count
    }
    

    A few Go details:

    • Parameters are copies. Assigning to n inside the function changes only the function's own copy, so the caller's number is untouched.
    • Operator precedence. In Go, & binds tighter than + and -, so the parentheses around n - 1 are required: they make the subtraction happen first.
    • int is 64 bits here. The lesson's values fit easily, with room to spare.

    Complexity

    Time: O(k), where k is the number of 1 bits. Each pass removes one 1 bit, so the loop runs exactly k times: 3 times for 11, once for 128, and 30 times for 2147483645. For values up to 2147483647 that is at most 31 passes.

    Space: O(1). The function keeps two integers, count and n.

    Edge cases and common mistakes

    • Zero. hammingWeight(0) skips the loop and returns 0.
    • A power of two. There is a single 1 bit, so the loop runs once: hammingWeight(128) is 1.
    • Counting before the loop condition. Increment count inside the loop, once per removed bit. Starting it at 1, or incrementing after the loop, is off by one.
    • Dropping the parentheses. n & n - 1 is read as (n & n) - 1, because & binds tighter than - in Go. For n = 12 it gives 11 instead of 8, so the loop would only count down by one and return n.
    • Using n % 2 and n / 2. This also works, but it passes over the 0 bits too, which is the slower O(log n) approach.

    Testing

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