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

How do you check if a number is a power of two using bit manipulation?

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

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

Nortren·

How do you check if a number is a power of two using bit manipulation?

0:34

A power of two in binary has exactly one bit set: 1, 10, 100, 1000, and so on. The number minus one flips all bits below the set bit and clears the set bit itself: 1000 minus one equals 0111. The bitwise AND of a power of two and itself minus one is always zero. So the check is: the number is greater than zero and the number AND the number minus one equals zero. This runs in O of one time. This trick works because only powers of two have a single set bit. Numbers that are not powers of two have multiple set bits, so their AND with themselves minus one is nonzero.
neetcode.io