Skip to main content

Number of 1 Bits

Count the number of 1 bits in the binary representation Example: 11 (binary: 1011) => 3

The trick is `n &= n - 1`, which clears the lowest set bit. I loop once per one-bit instead of walking all thirty-two.

Examples

You write

hamming_weight(n: int)

  1. Example 1

    Input
    11
    returns
    3
  2. Example 2

    Input
    128
    returns
    1

The pattern behind it

Bit Manipulation

I reach for it when

  • The statement bans extra space or restricts operators.
  • Numbers act as flags, masks or XOR pairs.

Say this before you type. Say what each bit means in this problem before you shift or mask anything.

All 12 Bit Manipulation problems

Meet Coco

Coco is an AI study partner, not a person. She listens while you explain your code, asks what a line does and never hands you the fix. Sign in free to type with Coco, up to a daily limit. The editor and Run stay open without an account. Anyone can open the editor and run their code.

1Number of 1 Bitseasy