Start learning free

LESSON 304 OF 314 · BIT MANIPULATION

Number of 1 Bits in Kotlin: Clearing the Lowest Set Bit in O(k)

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

    KOTLIN · BIT MANIPULATION

    Number Of 1 Bits in Kotlin, explained

    Problem overview

    The function hammingWeight receives a non-negative Int named 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, which has three 1 bits, so the answer is 3. For n = 128, which is 10000000, the answer is 1. The value 2147483645 has 31 binary digits and all but one of them are 1, so the answer is 30.

    Approach: remove one 1 bit per pass

    The obvious method checks all 32 bits one by one. The statement asks for O(k) time instead, where k is the number of 1 bits, so the loop should run once per 1 bit and skip the zeros.

    The trick comes from what subtracting 1 does in binary. The lowest 1 bit turns into 0, every 0 below it turns into 1, and the bits above stay as they are. For example, 12 is 1100 and 11 is 1011. Then n and (n - 1) keeps only the bits that are 1 in both numbers, which is every bit above the lowest 1 bit and nothing else. In short, n and (n - 1) is n with its lowest 1 bit cleared: 1100 and 1011 is 1000.

    Repeat that until the number is 0, and count the repetitions. Each pass clears exactly one 1 bit, so the number of passes equals the number of 1 bits.

    Step by step

    1. Copy n into a var named num. The loop changes the number, and a Kotlin parameter can't be reassigned.
    2. Start count at 0.
    3. Loop while num != 0. Once the last 1 bit is cleared, the number is 0 and the loop ends.
    4. Clear the lowest 1 bit: num = num and (num - 1). In Kotlin and is the bitwise AND, written as a word.
    5. Add 1 to count. One pass cleared one bit.
    6. Return count.

    The solution in Kotlin

    class Solution {
        fun hammingWeight(n: Int): Int {
            var num = n
            var count = 0
            while (num != 0) {
                num = num and (num - 1)
                count++
            }
            return count
        }
    }
    

    Here are the passes for n = 11:

    1011 and 1010 = 1010
    1010 and 1001 = 1000
    1000 and 111 = 0
    

    There are three passes, so the function returns 3.

    The Kotlin details worth knowing:

    • Bitwise operators are words. Kotlin has no &. It uses the infix functions and, or, xor, shl and shr.
    • Precedence. Named infix functions like and bind more loosely than + and -, so num and num - 1 means the same as num and (num - 1). The parentheses are there for the reader.
    • Parameters are read-only, which is why num exists.
    • Negative values. The lesson's tests use non-negative numbers, but the same loop also works on a negative Int: hammingWeight(-1) returns 32, since -1 has all 32 bits set.

    Complexity

    Time: O(k), where k is the number of 1 bits. Each pass clears one, and k is at most 31 for these values.

    Space: O(1). The function keeps num and count.

    Edge cases and common mistakes

    • Zero. The loop doesn't run, and the function returns 0.
    • Powers of two. They have one 1 bit, so the loop runs once: 128 and 127 is 0.
    • All ones. Int.MAX_VALUE, which is 2147483647, has 31 1 bits, and the function returns 31.
    • Using n and 1 with a shift also counts correctly, but it takes a pass for every bit up to the highest 1, not only for the 1 bits.
    • Forgetting the copy. Writing n = n and (n - 1) inside the function doesn't compile, because n is a read-only parameter.

    Testing

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