Search code examples
binarybit-manipulationbitwise-operators

How to check efficiently if in number binary representation all next bit is different?


I need to write the function to check if the number binary representation doesn't contain duplications. For example, the function must return true if N equals to 42, because bin(42) equals to 101010, but if N equals to 45 the function must return false, because of binary representation of 45 which equals to 101101 and which contains duplicates 11.


Solution

  • This allows only bits that alternate between 0 and 1, plus possibly leading zeros.

    One way to check this is to look at (N << 2) | N. If N is of the correct form, then this is equal to N << 2, except for bit 0 or 1. We can compensate for that as follows:

    unsigned N2 = N << 2;
    return (N | N2) <= (N2 | 2);