How to check if a number is a power of two for O(1)

How to check if a number is a power of two for O(1)

dev.to - Aug 13

Image description

In binary representation, numbers consist of 0 and 1. And it just so happens that all powers of two are 10*.
For example, 2 -> 10, 8 -> 1000, and so on.
When we do a comparison of number & number - 1 == 0, we check 100 & 011, which will always yield 0.

3 → 11. 3 & 2 => 11 & 10 = 1.

MORE ARTICLES