Start learning free

LESSON 304 OF 314 · BIT MANIPULATION

Number of 1 Bits in C++: 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

    C++ · BIT MANIPULATION

    Number Of 1 Bits in C++, explained

    Problem overview

    The method hammingWeight takes a non-negative int n 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, it is 1. For n = 2147483645, whose 31 binary digits are all 1 except one, it is 30.

    The statement 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 time

    The obvious way tests every bit position, one pass for each of the 31 or 32 bits. That takes the same time whether the number has one 1 bit or thirty. The lesson uses a trick that does one pass per 1 bit.

    Subtracting 1 from a number turns its lowest 1 bit into 0 and every 0 below that bit into 1; higher bits stay as they are. So n & (n - 1) keeps the higher bits and clears the lowest 1 bit and everything below it, which was already 0. In short, it removes exactly one 1 bit. Repeating this until n is 0 takes k rounds, and counting the rounds gives the answer.

    For n = 11, the rounds produce 1010 (10), then 1000 (8), then 0. That is three rounds, so the answer is 3. Running the lesson's code on that value, n takes the values 10, 8 and 0 in turn.

    Step by step

    1. Create count and start it at 0.
    2. Loop while n != 0. When the last 1 bit has been removed, n is 0 and the loop ends.
    3. Clear the lowest 1 bit with n = n & (n - 1).
    4. Increase count: one bit was removed.
    5. Return count.

    The solution in C++

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

    C++ details worth knowing:

    • Precedence. & binds more loosely than +, - and even ==. Here n & n - 1 would mean the same thing, but the parentheses make it readable, and in an expression like i & 1 + 1 the addition happens first: with i = 3 it gives 2, not 1.
    • n is a copy. The parameter is passed by value, so the loop can change it freely without touching the caller's number.
    • Why the input range matters. The constraints keep n between 0 and 2,147,483,647, so it is never negative and n - 1 never underflows the int. For n = 0 the loop doesn't run and the result is 0.

    Complexity

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

    Space: O(1). Only count and the changing copy of n are kept.

    Edge cases and common mistakes

    • Zero. n = 0 has no 1 bits; the loop is skipped and 0 is returned.
    • Powers of two. 128 has one 1 bit, so the loop runs once: 128 & 127 is 0.
    • The largest input. n = 2147483647 has 31 bits, all 1, and the answer is 31.
    • Using && instead of &. && is the logical AND, which gives 0 or 1, not a bit-by-bit result.
    • Forgetting to assign. Writing n & (n - 1); alone computes a value and throws it away, so the loop never ends.

    Testing

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