Skip to content
mlmentorship

Number of 1 Bits

Clear the lowest remaining one at each step, with an explicit nonnegative or fixed-width integer contract.

Published · 14 min read ·Core ·Mixed

ML breadth · active recall

Practice before you read

8 minutes. Explain the mechanism, why it works, when it fails, and one alternative.

ML breadth · closed-book attempt

Number of 1 Bits

Explain the mechanism, why it works, when it fails, and one alternative.

Problem

Input. A nonnegative integer value. Output. Return the number of binary digits equal to one, also called the set-bit count or Hamming weight. Rules. Count bits, not the integer's decimal digits or its total binary width. Leading zeros contribute nothing. Zero returns zero; negative integers require a separate finite-width contract below. Example. Integer 11, binary 1011, returns 3. Integer 8, binary 1000, returns 1.

08:00recommended time

Closing or reloading clears the scratchpad. Only score, weak rubric dimensions, attempt count, and retry date can be stored locally.

30-second answer map

Each value & (value - 1) update removes one lowest set bit, so the number of loop iterations is the Hamming weight.

Problem trace

Each pass clears one set bit; empty positions need no pass

Each pass clears one set bit; empty positions need no passThe lowest set bit disappears each pass. Binary 1100 becomes 1000, then 0000. Two passes count two set bits, not four bit positions. Empty positions need no clearing pass.One pass clears one remaining lowone, not one arbitrary positionInitial twelve: binary 11001100Lowest one cleared: 12 becomes 81000Final one cleared: 8 becomes 00000Two passes remove two set bits. Emptypositions need no clearing passes.
Read it this way: The lowest set bit disappears each pass. Binary 1100 becomes 1000, then 0000. Two passes count two set bits, not four bit positions. Empty positions need no clearing pass. Does an empty low position require an extra clearing pass?
Full interview answer 14 min read

Count how many one bits occur in the binary representation of a nonnegative integer.

Problem

Input. A nonnegative integer value.

Output. Return the number of binary digits equal to one, also called the set-bit count or Hamming weight.

Rules. Count bits, not the integer’s decimal digits or its total binary width. Leading zeros contribute nothing. Zero returns zero; negative integers require a separate finite-width contract below.

Example. Integer 11, binary 1011, returns 3. Integer 8, binary 1000, returns 1.

Picture

In 00101101, the ones have bit positions 0,2,3,5. Positions count from the right, unlike left-to-right array indices.

The labels below the cells are bit positions. Eight cells display this example; they do not restrict the reference to eight-bit inputs.

Problem trace

Separate fixed-width pattern: clear one lowest remaining set bit per pass

Input and goalCount the set bits in an integer.
Initialize value and countStart at 45 = 00101101 with count zero; the next removed bit is bit 0.
07061504131201b=010
value45count0loopCondition45 != 0
b
7
value
45
count
0

Recognize it
The task asks for the population count of an integer, and work should scale with the number of 1 bits rather than the fixed bit width.
Keep true
After count iterations, count equals the number of 1 bits removed from the original value, and the current value contains every original set bit not yet removed.
Reuse it
Use x & (x - 1) whenever progress is defined by deleting one set bit; related uses include power-of-two tests, iterating subsets, and finding the lowest set-bit contribution.
Start at 45 = 00101101 with count zero; the next removed bit is bit 0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does each iteration remove exactly one set bit? Why are only four iterations needed for 45?
Reference drawing

Problem trace

Each pass clears one set bit; empty positions need no pass

Each pass clears one set bit; empty positions need no passThe lowest set bit disappears each pass. Binary 1100 becomes 1000, then 0000. Two passes count two set bits, not four bit positions. Empty positions need no clearing pass.One pass clears one remaining lowone, not one arbitrary positionInitial twelve: binary 11001100Lowest one cleared: 12 becomes 81000Final one cleared: 8 becomes 00000Two passes remove two set bits. Emptypositions need no clearing passes.
Execution trace
Input and goalCount the set bits in an integer.
Initialize value and countStart at 45 = 00101101 with count zero; the next removed bit is bit 0.
07061504131201b=010
value45count0loopCondition45 != 0
b
7
value
45
count
0

Recognize it
The task asks for the population count of an integer, and work should scale with the number of 1 bits rather than the fixed bit width.
Keep true
After count iterations, count equals the number of 1 bits removed from the original value, and the current value contains every original set bit not yet removed.
Reuse it
Use x & (x - 1) whenever progress is defined by deleting one set bit; related uses include power-of-two tests, iterating subsets, and finding the lowest set-bit contribution.
Start at 45 = 00101101 with count zero; the next removed bit is bit 0. Step through the frames to watch the state change. The last frame shows the answer or the stopping condition.
Check: Why does each iteration remove exactly one set bit? Why are only four iterations needed for 45?
Read it this way: The lowest set bit disappears each pass. Binary 1100 becomes 1000, then 0000. Two passes count two set bits, not four bit positions. Empty positions need no clearing pass. Does an empty low position require an extra clearing pass?

Code

From the lowest one to the right edge, the current suffix is 100...0.

Subtracting one changes that suffix to 011...1. AND with the original clears exactly that one and keeps the trailing zeros.

Higher bits stay unchanged.

def hamming_weight(value: int) -> int:
   count = 0
   while value:
      value &= value - 1
      count += 1
   return count

Removed Versus Remaining

count records removed original ones. value contains exactly the original ones not yet removed.

The trace follows 45 -> 44 -> 40 -> 32 -> 0, clearing positions 0,2,3,5. Four deletions give count four.

For nonnegative input, every iteration reduces the remaining population by one. Termination therefore follows from a finite initial population.

An unmasked negative Python value violates this argument. Starting at -1 gives -2,-4,-8,..., never zero.

Cost

For a fixed-width machine word, set bits require operations and constant word storage.

Python’s bit-operation costs and integer storage depend on bit length. A constant number of integer slots is not constant bit storage.

Recall: What decreases each round? The number of remaining ones, not necessarily the represented word’s width.

Interpret a Finite Signed Pattern

Choose this when: A protocol or machine word supplies a fixed width.

Keep only the low width bits before calling the reference. This interprets the integer modulo , including negative inputs.

def fixed_width_weight(value, width):
   if width < 0:
      raise ValueError("negative width")
   return hamming_weight(value & ((1 << width) - 1))

The helper requires integer inputs. Width zero gives zero; a negative width raises ValueError.

At width eight, -1 has eight ones and -2 has seven. Positive 257 truncates to one.

This is not population count of the absolute value. Python’s (-1).bit_count() reports one, not the eight ones of an eight-bit signed representation.

Mask construction and retained integer storage depend on width. The clearing loop performs one iteration per retained one.

Return the Set Positions

Choose this when: The sparse bit locations are required, rather than just their count.

value & -value isolates the lowest one. Its bit length minus one gives its zero-based significance.

def set_bit_positions(value):
   if value < 0:
      raise ValueError("nonnegative value required")
   positions = []
   while value:
      lowest = value & -value
      positions.append(lowest.bit_length() - 1)
      value &= value - 1
   return positions

For 45, the answer is [0,2,3,5]. Their powers of two sum back to 45. Zero returns []; negative input raises ValueError.

Positions arrive in increasing order. Output storage is integer entries, in addition to width-dependent working integers.

Transfer

For positive value, value & (value - 1) is smaller and has one fewer one. Reusing its precomputed count gives the recurrence in Counting Bits.