Example 1
- Input
- n = 00000000000000000000000000001011
- Output
- 3
The binary form of 11 holds three 1 bits.
Count the 1 bits in the 32-bit binary form of an unsigned integer, treating a signed input with the same bit pattern identically.
Given an integer representing a 32-bit unsigned bit pattern, return the number of one bits, called its Hamming weight. The shown inputs are binary representations for readability; the functions receive integers, not strings.
This page retains the generalized unsigned 32-bit form of the problem, including zero and patterns with the high bit set. A signed Java int may carry the same pattern, such as -3 for unsigned 4294967293. The current positive-integer version with 1 <= n <= 2147483647 is a subset of this contract.
The binary form of 11 holds three 1 bits.
The binary form of 128 holds a single 1 bit.
This 32-bit pattern holds thirty-one 1 bits (it reads as -3 as a signed int).
No bit is set. The fixed scan adds zero 32 times; the erasure approach returns immediately without any iteration.
A set bit is simply a binary digit equal to one; leading zeros contribute nothing. Example 1 is decimal 11, whose binary form 1011 has three ones. Inspecting each of 32 positions counts them directly. Alternatively, subtracting one and ANDing with the old pattern erases one set bit at a time, so counting erasures skips zero positions. Signed and unsigned carriers must describe the same fixed 32-bit pattern.
Reveal Scan All 32 Bits: intuition, complexity, and code
n & 1 is 1 exactly when the current last bit is set.n & (n - 1) and count erasures until nothing remains.n & (n - 1) always drops the lowest set bit — the single most useful bit-manipulation identity for counting, clearing, and power-of-two tests.