White Cheese (Burgos) - Developing
White Cheese (Burgos) - Developing
Very new or simple note, likely to evolve and change.
Click the cheese icon to learn more

Brian Kernighan's Algorithm

Author: guiferviz Created: Last Modified:

An Algorithm used to count the number of active bits (bits set to one in an integer).

def count_set_bits_kernighan(n):
	count = 0
	while n:
		n &= (n - 1)
		count += 1
	return count

The complexity is O(m)\mathcal{O}(m), where mm is the number of set bits in the integer. This is typically more efficient than iterating over all bits, especially for sparse integers.