To check if alternate bits are set, Carry out the following operations:
- First XOR the number n and (n >> 1). If alternate bits are set then this will produce all 1’s. Let us call the result as m
- To check is all the bits are set to 1, AND m with m + 1 and the result will be 0
Example:
Let us say n = 5.
n 101
(n >> 1) 010
——————— XOR
m 111
Now,
m 0111
m+1 1000
———————– AND
result 0000