Start learning free

LESSON 304 OF 314 · BIT MANIPULATION

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

    C# · BIT MANIPULATION

    Number Of 1 Bits in C#, explained

    Problem overview

    The method HammingWeight receives a non-negative int n and returns how many 1 bits its binary form has, also called its Hamming weight. For n = 11, the binary form is 1011, so the result is 3. For 128, the binary form is 10000000: one 1 bit. For 2147483645, 30 of its 31 binary digits are 1, so the result is 30.

    Approach: remove one 1 bit per pass

    The obvious way is to test all 32 bits, shifting right each time. That always takes 32 steps. This lesson's loop runs only once per 1 bit, so 128 takes one pass, not 32.

    The idea rests on what subtracting 1 does in binary. The lowest 1 bit of n turns into 0, every 0 below it turns into 1, and the higher bits stay the same. For 12 (1100), 12 - 1 = 11 (1011). Now the two numbers have a 1 in the same column only above the old lowest 1 bit, so n & (n - 1) is n with exactly its lowest 1 bit cleared: 1100 & 1011 = 1000.

    Repeat that until n is 0 and count the repetitions. Each repetition removes one 1 bit, so the count equals the number of 1 bits.

    Approach compared with checking every bit

    The straightforward alternative tests each of the 32 positions with (n >> i) & 1 and adds the results. It gives the same answers (3, 1 and 30 for 11, 128 and 2147483645), but it always makes 32 passes, whatever n is. Clearing the lowest bit makes the work depend on the number of 1 bits instead, which is why the lesson asks for O(k).

    .NET also has a built-in, System.Numerics.BitOperations.PopCount, which takes a uint and returns the same count (3 for 11). The exercise asks you to build the counting yourself.

    Step by step

    1. Create count, an int starting at 0.
    2. Loop while n != 0. After the last 1 bit is removed, n is 0 and the loop ends.
    3. Clear the lowest 1 bit: n = n & (n - 1);. The & operator is bitwise AND: a result bit is 1 only where both numbers have a 1.
    4. Add 1 to count in the same pass.
    5. Return count.

    Tracing n = 11, the value of n in binary after each pass is:

    1010
    1000
    0
    

    Three passes, so the answer is 3.

    The solution in C#

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

    Details worth knowing:

    • Parameters are copies. Changing n inside the method doesn't change the caller's variable.
    • Precedence. In C#, - binds tighter than &, so n & n - 1 would mean the same, but the parentheses make the intent clear.
    • No overflow here. n - 1 only runs while n is not 0, and n is never negative, so it can't go below 0 or wrap.

    Complexity

    Time: O(k), where k is the number of 1 bits, at most 31 for these values. Space: O(1): two int variables.

    Edge cases and common mistakes

    • Negative values. They are outside the lesson's range. The loop still ends for them: -1, with all 32 bits set, returns 32.
    • Zero. The loop never runs and the method returns 0.
    • The largest value. int.MaxValue (2147483647) has 31 ones and returns 31.
    • Powers of two. Each has one 1 bit, so 1 and 128 both return 1.
    • Forgetting the increment. count must go up once per pass, one for each bit removed.

    Testing

    • 11 gives 3.
    • 128 gives 1.
    • 2147483645 gives 30.
    • 0 gives 0.
    • 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