Workspace Number Of 1 Bits
0d
Back to questionsDSA Visualizers: 388 Coding Questions

Number of Set Bits visualizer

Count the set bits in the binary form of nonnegative target. The values list is unused.

EXECUTION LAB

Count the set bits in the binary form of nonnegative target. The values list is unused.

Input and constraints
  • Target must be nonnegative.
  • Use at most 32 integers. Each numeric input is between -1000 and 1000.

Code inspector

def solve(values, target):
bits = target
count = 0
while (bits > 0):
bits = (bits & (bits - 1))
count = (count + 1)
return count

Visualizer

Step 1 of 4

Empty array

Clear the lowest set bit in the current value

Clear the lowest set bit in 13.

Variable watch

bits 13count 0

Step explanation

Clear the lowest set bit in 13.

comparisons 1reads 0writes 0swaps 0recursiveCalls 0
Educational simulation · O(number of set bits) time · O(1) space

Worked explanation

Remove one lit lamp at a time and count the removals.

Guided solution

Masking a positive number with one less clears its lowest set bit.

O(number of set bits) time · O(1) auxiliary space

Examples

Worked example · {"values":[],"target":13} ⇒ 3

Edge case 1 · {"values":[],"target":0} ⇒ 0

Edge case 2 · {"values":[],"target":512} ⇒ 1

Progressive hints

Hint 1Remove one lit lamp at a time and count the removals.
Hint 2Masking a positive number with one less clears its lowest set bit.
Hint 3Step through the worked example and inspect the highlighted variables before each update.

Common mistake

The routine assumes a nonnegative integer with a finite unsigned representation.

Interview follow-up

Why does subtracting one change all low bits up to the first one?

Continue learning

Practice related DSA questions in the same topic.