Problem
Explain what the following code does: ((n & (n-1)) == 0).
Solution
When we have A & B == 0, it means that A and B have no common 1s, i.e. any two bits at the same positions of A and B are either different from each other, or two 0s.
It works because a binary power of two is of the form 1000…000 and subtracting one will give you 111…111. Then, when you AND those together, you get zero, such as with:
|
|
Any non-power-of-two input value will not give you zero when you perform that operation. For example, let’s try all the 3-bit combinations:
|
|
This can be used in Power of Two.