Start learning free

LESSON 304 OF 314 · BIT MANIPULATION

Number of 1 Bits in JavaScript: O(k) with n & (n - 1)

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

    JAVASCRIPT · BIT MANIPULATION

    Number Of 1 Bits in JavaScript, explained

    Problem overview

    The method hammingWeight(n) 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, which has three 1 bits, so the answer is 3. For n = 128, which is 10000000, the answer is 1.

    The statement asks for O(k) time, where k is the number of 1 bits, rather than one step per digit, and O(1) extra space.

    Approach: remove the lowest 1 bit each time

    The obvious method checks each of the 31 bit positions in turn. This lesson uses a faster trick that does one step per 1 bit and skips the zeros.

    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 12 (1100), 12 - 1 is 11 (1011). Now take the bitwise AND of the two: a result bit is 1 only where both numbers have a 1. Everything below the lowest 1 bit is 0 in the original, so it cancels, the lowest 1 bit itself is 0 in the other number, and the bits above are identical in both, so they stay. The result, 1000, is 12 with its lowest 1 bit removed.

    So n & (n - 1) removes exactly one 1 bit. Repeat until n reaches 0 and count the repetitions. For 12 the loop runs twice: 1100 & 1011 gives 1000, then 1000 & 0111 gives 0.

    Step by step

    1. Create count with let, starting at 0. It counts the bits removed.
    2. Loop while n !== 0. The loop ends right after the last 1 bit is removed.
    3. Replace n with n & (n - 1). This is the key line. The parentheses matter for readability: the subtraction happens first because - binds tighter than &.
    4. Add 1 to count inside the loop: one pass removed one bit.
    5. Return count after the loop.

    The solution in JavaScript

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

    JavaScript details that matter here:

    • Bitwise operators work on 32 bits. JavaScript numbers are doubles, but &, |, ^ and the shifts first convert their operands to signed 32-bit integers. The lesson's range, up to 2147483647 (2**31 - 1), fits, so every bit of n is counted correctly.
    • Larger values are truncated. Outside the lesson's range, the conversion keeps only the low 32 bits. hammingWeight(4294967299) returns 2, although 4294967299 (2**32 + 3) has three 1 bits, because the bit above the 32nd is lost. Don't rely on the method beyond 31 bits.
    • The loop condition. n !== 0 is a strict comparison to the number 0. After n & (n - 1), n is always an int32, so it reaches exactly 0.
    • Reassigning a parameter is allowed. It changes only the local copy of n.

    Complexity

    Time: O(k), where k is the number of 1 bits. Each pass removes one, so there are exactly k passes, at most 31 for the values in this lesson. For 128, with a single 1 bit, the loop runs once even though the number has eight digits.

    Space: O(1). Only count and the changing n are stored.

    Edge cases and common mistakes

    • Zero. hammingWeight(0) returns 0 because the loop never runs.
    • All bits set. 2147483647 is 31 ones in a row and returns 31. The loop runs 31 times.
    • A single bit. Powers of two, such as 1 or 128, return 1.
    • Missing parentheses. n & n - 1 happens to parse the same way, because - binds tighter than &. Writing the parentheses makes the intent clear and avoids mistakes when mixing operators like + and & in other code.
    • Forgetting to update n. Writing n & (n - 1) without assigning the result leaves n unchanged, and the loop never ends.
    • Using == or !n. These work here, but !== 0 states what you mean without type conversions.

    Testing

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