Start learning free

LESSON 304 OF 314 · BIT MANIPULATION

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

    TYPESCRIPT · BIT MANIPULATION

    Number Of 1 Bits in TypeScript, explained

    Problem overview

    The method hammingWeight receives a non-negative integer n, up to 2,147,483,647, and returns how many 1 bits its binary form has.

    For n = 11 the binary form is 1011, which has three 1 bits, so the result is 3. For 128, which is 10000000, the result is 1. For 2147483645, which is thirty-one digits with a single 0, the result is 30.

    The note 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 loop tests the lowest bit of n, shifts n right and repeats, which takes one pass for every binary digit, 1 or 0. This lesson uses a trick that skips the zeros: each pass removes exactly one 1 bit, so the loop runs k times.

    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 higher bits stay the same. For n = 12, which is 1100, n - 1 is 11, which is 1011. Taking the bitwise AND of the two keeps only the bits that are 1 in both, and the changed bits can't match, so n & (n - 1) is n with its lowest 1 bit removed: 1100 & 1011 is 1000. Repeat until n is 0 and count the passes.

    For n = 11 the passes are:

    n      n - 1  n & (n - 1)
    1011   1010   1010
    1010   1001   1000
    1000   0111   0000
    

    Three passes, so three 1 bits.

    Step by step

    1. Start count at 0, declared with let because it changes.
    2. Loop while n !== 0. Each pass removes one 1 bit, so n reaches 0 right after its last 1 bit is gone. A number with no 1 bits, such as 0, skips the loop.
    3. Clear the lowest 1 bit: n = n & (n - 1). The bitwise AND gives a 1 only where both numbers have a 1.
    4. Add 1 to count with ++, since one bit was removed.
    5. Return count.

    The solution in TypeScript

    class Solution {
        hammingWeight(n: number): number {
            let count = 0;
            while (n !== 0) {
                n = n & (n - 1);
                count++;
            }
            return count;
        }
    }
    

    Some TypeScript details:

    • Parameters can be reassigned. n is an ordinary local variable inside the method, so the loop can overwrite it. The caller's number is not affected, because numbers are passed by value.
    • Bitwise operators work on 32-bit integers. number is a double, but & converts both operands to signed 32-bit integers first and gives back a number. For the values in this lesson, 0 up to 2147483647, that conversion changes nothing.
    • The parentheses matter. Subtraction binds tighter than &, so n & n - 1 would also mean n & (n - 1), but the parentheses make the intent clear.
    • Types are erased. The annotations on n and the return value exist only for the compiler.

    Complexity

    Time: O(k), where k is the number of 1 bits. Each pass removes exactly one of them, and the loop stops when none are left. For these inputs that is at most 31 passes.

    Space: O(1). The method keeps one counter and the number it is changing.

    Edge cases and common mistakes

    • Zero. hammingWeight(0) returns 0: the loop body never runs.
    • A power of two. 128 has one 1 bit, so it takes a single pass and the result is 1.
    • All ones. 2147483647, thirty-one 1 bits, returns 31.
    • Looping on the wrong condition. Testing n > 0 works for the lesson's inputs, but n !== 0 also handles values that bitwise operators turn negative.
    • Forgetting to update n. Writing n & (n - 1) without assigning the result leaves n unchanged, and the loop never ends.
    • Beyond the lesson's range. A number such as 4294967295 is outside the constraints, but bitwise operators treat it as the 32-bit pattern of all ones, and this code returns 32 for it. Numbers of 4,294,967,296 or more lose their upper bits, so this approach isn't meant for them.

    Testing

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