MemotivaLeetCode Patterns Flashcards: Bit Manipulation, XOR Tricks, Masks, Powers of Two

How do you count the number of set bits in an integer?

LeetCode Patterns Flashcards: Bit Manipulation, XOR Tricks, Masks, Powers of Two

Аудио-карточка · 0:29

Nortren·

How do you count the number of set bits in an integer?

0:29

The Brian Kernighan algorithm repeatedly clears the lowest set bit using the operation n AND n minus one, counting how many times this operation is needed until n reaches zero. Each operation removes exactly one set bit, so the loop runs exactly k times where k is the number of set bits, which is more efficient than checking all 32 bits. For the Hamming distance problem, first XOR two numbers to get a result where set bits represent positions that differ, then count the set bits of the XOR result. Counting set bits is also called the population count or popcount.
neetcode.io