Power of two check

Decide whether a number is a power of two with a single AND, no loop or log needed.

Time O(1)Space O(1)Code C#
Watch it animatedStep through it, with the running line highlighted. Free with an account.

The idea

A power of two has exactly one set bit, like 01000000. Subtracting 1 flips that single bit to 0 and turns every bit below it to 1, like 00111111. ANDing the two values together then leaves nothing in common, so the result is 0 only when n started with a single set bit.

Code

public static bool IsPowerOfTwo(int n) {
    if (n <= 0) return false;
    int m = n - 1;
    int r = n & m; // clears the lowest set bit, if any
    return r == 0;
}

Tips

In the .NET library

If n has more than one set bit, n & (n - 1) only clears the lowest one and leaves the rest, so the result is never 0. That is what makes this test exact.