Start learning free

LESSON 304 OF 314 · BIT MANIPULATION

Number of 1 Bits in Swift: n & (n - 1) in O(k) Time

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

    SWIFT · BIT MANIPULATION

    Number Of 1 Bits in Swift, explained

    Problem overview

    The method hammingWeight(_ n: Int) -> Int 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, so the answer is 3. For n = 128, which is 10000000, the answer is 1. For n = 2147483645 the answer is 30: its binary form has 31 digits and exactly one of them is 0.

    The lesson asks for O(k) time, where k is the number of 1 bits, and O(1) extra space.

    Approach: remove the lowest 1 bit each pass

    The obvious method checks all the bits one by one: look at the lowest bit, shift right, repeat. That takes a pass per bit position, including the 0s. The goal here is one pass per 1 bit.

    The idea rests on what subtracting 1 does in binary. The lowest 1 bit becomes 0, every 0 below it becomes 1, and the higher bits stay the same. For example, 12 is 1100 and 11 is 1011. Now take the bitwise AND of the two numbers. Bits above the lowest 1 are the same in both, so they survive. The lowest 1 is 1 in n but 0 in n - 1, so it disappears. The bits below it are 0 in n, so they stay 0. The result, n & (n - 1), is n with its lowest 1 bit removed: 1100 & 1011 is 1000.

    So repeat that operation until n becomes 0 and count the repetitions. Each repetition removes exactly one 1 bit, so the loop runs k times.

    Step by step

    1. Copy n into var num. The loop changes it, and a Swift parameter is a constant.
    2. Create var count and start it at 0.
    3. Loop while num != 0. A number with no 1 bits left is 0.
    4. Remove the lowest 1 bit with num = num & (num - 1).
    5. Add 1 to count in the same pass: one bit was removed.
    6. Return count after the loop.

    The solution in Swift

    class Solution {
        func hammingWeight(_ n: Int) -> Int {
            var num = n
            var count = 0
            while num != 0 {
                num = num & (num - 1)
                count += 1
            }
            return count
        }
    }
    

    The Swift details worth a closer look:

    • Int is 64 bits. The values in this lesson fit in 31 bits, so the high bits are all 0 and never counted.
    • Precedence. The parentheses in num & (num - 1) are not needed for precedence, since Swift's & binds tighter than most operators, but they make the intent clear.
    • Overflow traps. Swift arithmetic that overflows stops the program. With non-negative input, num - 1 never overflows: the smallest value it sees is 1, which becomes 0.
    • The parameter is a constant. Writing n = n & (n - 1) directly is a compile error, which is why the code copies it to num.

    Tracing 11

    Each pass for n = 11, with the binary form of num before and after:

    1011 -> 1010
    1010 -> 1000
    1000 -> 0
    

    Three passes, so the result is 3.

    Complexity

    Time: O(k). Each pass removes one 1 bit, so the loop runs exactly k times, at most 31 for the values allowed here.

    Space: O(1). Only num and count are stored.

    Edge cases and common mistakes

    • Zero. The loop never runs and the result is 0.
    • A power of two. There is a single 1 bit, so one pass is enough: 128 gives 1.
    • All bits set. 2147483647, which is 31 ones, gives 31.
    • Negative input. The lesson only gives non-negative values. A negative Int has its sign bit set, so the loop eventually reaches the smallest Int, and num - 1 then overflows and crashes the program.
    • Using | or ^ instead of &. Only AND removes the lowest 1 bit.
    • Forgetting to update num. Computing num & (num - 1) without assigning it back leaves num unchanged, and the loop never ends.

    Swift can count the bits directly with the nonzeroBitCount property: 11.nonzeroBitCount is 3. The loop above is the technique the lesson practises, and it is useful whenever you need to work with the lowest set bit.

    Testing

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