Number of 1 Bits

easy

Count the number of set bits (1s) in a binary number (Hamming Weight)

Number of 1 Bits

Key Insight

n & (n-1) clears the lowest 1-bit. Count iterations until n=0.

Step 1Input
n
11
=
0
0
0
0
1
0
1
1
76543210
1011 has ? ones

Count 1-bits in 11 (binary: 1011)

1 / 5

Learn the Pattern

Practice the Code

Step-by-Step Walkthrough: Number of 1 Bits

n & (n-1) clears the lowest 1-bit. Count iterations until n=0.

  1. Input

    Count 1-bits in 11 (binary: 1011)

  2. First Clear

    11 & 10 = 10. Cleared lowest bit. Count=1.

  3. Second Clear

    10 & 9 = 8. Count=2.

  4. Third Clear

    8 & 7 = 0. Count=3. n is now 0.

  5. Result

    11 has 3 one-bits.