Start learning free

LESSON 304 OF 314 · BIT MANIPULATION

Number of 1 Bits in Scala: Clearing the Lowest 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

    SCALA · BIT MANIPULATION

    Number Of 1 Bits in Scala, explained

    Problem overview

    The method hammingWeight(n: Int): Int takes a non-negative integer and returns how many 1 bits its binary form has. For n = 11, which is 1011, the answer is 3. For n = 128, which is 10000000, the answer is 1. And 2147483645, which is thirty-one binary digits with a single 0, gives 30.

    Approach: remove one 1 bit per pass

    The obvious way tests all 32 bit positions, one by one. The lesson's way does one pass per 1 bit instead, so the time is O(k) for k 1 bits.

    The idea is in what subtracting 1 does to a binary number. The lowest 1 bit becomes 0, every 0 below it becomes 1, and the bits above stay the same. For 12 (1100), 12 - 1 is 11 (1011). Now AND the two: the bits above the lowest 1 match and survive, while the lowest 1 bit and everything below it meet a 0 in one of the two numbers. So n & (n - 1) is n with its lowest 1 bit removed: 1100 AND 1011 is 1000.

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

    Step by step

    1. Copy n into var num. Scala parameters can't be reassigned, and the loop has to change the number.
    2. Create var count, starting at 0.
    3. Loop while (num != 0): as soon as the last 1 bit is gone, the number is 0 and the loop ends.
    4. Inside, set num = num & (num - 1), which drops the lowest 1 bit.
    5. Add 1 to count in the same pass.
    6. Return count.

    The solution in Scala

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

    Scala details

    • & is bitwise AND on Int. It is a different operator from &&, which works on Booleans.
    • num and count are vars because they change; n is a parameter and is always read-only.
    • The loop condition is num != 0, not num > 0. For the non-negative inputs in this lesson both behave the same, but != 0 is the one that depends only on the bits.
    • return works in a method, but Scala usually leaves it out and ends with count as the last expression.

    Tracing n = 11

    Each pass shows num, num - 1 and their AND:

    1011 & 1010 = 1010
    1010 & 1001 = 1000
    1000 & 111 = 0

    Three passes ran, so the answer is 3. Leading zeros are not shown in the printed bits.

    Complexity

    Time is O(k), where k is the number of 1 bits: each pass removes one, and with at most 31 bits for these values the loop never runs more than 31 times. Space is O(1): two integers.

    Edge cases and common mistakes

    • Zero: hammingWeight(0) skips the loop and returns 0.
    • All bits set: 2147483647, the largest Int, has 31 ones and the method returns 31.
    • Power of two: a number with a single 1 bit, like 128, finishes after one pass, because 128 & 127 is 0. The same trick tests for a power of two.
    • Shifting instead: checking num & 1 and shifting right works too, but it takes one pass per bit position up to the highest 1 bit, not per 1 bit.
    • Missing parentheses: in num & (num - 1), the parentheses are needed because - binds tighter than &, but writing them makes the intent clear.

    More small inputs from the lesson's method: 1 returns 1, 12 returns 2, and 2147483645 returns 30.

    Keep going with Scala1,600+ step-by-step lessons, from your first line of code to coding interviews. Free to start.
    Start learning free