DrawCode Algorithm Visualizer • Bit Manipulation • Easy

Brian Kernighan's Algorithm

Tags: Bit, Popcount, Low Level, Optimization

1. One-Liner

Repeatedly do n &= n-1 to drop the lowest set bit; iteration count equals population count.


2. The Problem It Solves

Count bits in sparse integers, parity checks, and when hardware popcnt unavailable or disallowed.


3. The Core Idea

Subtracting 1 flips trailing zeros and lowest 1; AND clears that 1—each loop removes exactly one set bit.


4. How It Works (Step-by-Step)

StepAction
1c=0
2While n≠0: n &= n-1; c++
3Return c

5. Dry Run Example

n=12 (1100): iterations 1100→1000→0000 → two bits.


6. Key Properties

PropertyDetail
ComplexityO(number of 1s), not bit width
vs lookupTrade memory
UnsignedMind sign in Java

7. Where It Is Used

Domain / SystemUse
NetworkingHamming weight
CryptoParity side-channels careful
EmbeddedBit counting

8. Interview Tips

Compare to __builtin_popcount, SWAR broadword; know n&(n-1) also isolates lowest bit via n XOR (n&(n-1)).


9. Comparison with Other Algorithms

TechniqueNotes
Shift loopO(log n) always
Lookup tableO(1) time, space
Parallel popcountSIMD

10. Complexity

----
TimeO(k) k = popcount
SpaceO(1)

Implementation Example (PYTHON)

def count_set_bits(n):
    c = 0
    while n:
        n &= n - 1
        c += 1
    return c

Interactive Visualizer Workspace

Explore step-by-step interactive animations, memory state tracking, and live multi-language execution in DrawCode.

Launch Interactive Visualizer