Codacoda
Back to Academy

bitwise operations

Count Set Bits (Brian Kernighan's)

Brian Kernighan's algorithm counts the number of set bits (1s) in an integer by repeatedly clearing the lowest set bit using n & (n-1). Each iteration removes exactly one set bit, making it O(k) where k is the number of set bits rather than O(log n) for checking every bit position.

Use Cases

  • Calculating Hamming weight for error detection codes
  • Population count in bitmap indices and databases
  • Evaluating game board states in chess engines
  • Measuring similarity between binary feature vectors

Complexity Analysis

MetricBestAverageWorst
TimeO(1)O(k)O(log n)
SpaceO(1)

Visualization

Startn=130000110176543210Set bits so far: 0
Speed:1x
Count set bits of 13 (00001101) using Brian Kernighan's algorithm: n & (n-1) removes the rightmost set bit.Step 1 / 5

Implementation

Output

Click "Run Code" to see output...