Hacker News new | ask | show | jobs
by ColinWright 4567 days ago
The GP is correct, this is bit-twiddling code to test for a single bit being set in the int, and therefore being a power of 2, not simply a multiple of 2.

Broadly speaking, and ignoring edge cases, if N is a power of 2 then it has a single bit set. Subtracting one unsets that bit, so the AND of N and (N-1) is zero. On the other hand, if N is not a power of two then subtracting 1 leaves the top bit still set, so the AND is non-zero. Therefore taking the boolean NOT gives the right answer.

    00010000  Power of 2
    00001111  N-1
    --------
    00000000  -> 0

    00010110  Non power of 2
    00010101  N-1
    --------
    00010100  -> Non 0
Thus power of 2 is NOT( N & (N-1) ). Your examples are wrong because "!" is not bit-wise NOT, but boolean NOT. !0 = True, !N = False when N is non-zero.

It's actually wrong on the edge case of N=1, which is a power of 2.

1 comments

Thanks, you're right. I don't know why I would have ever thought "!" was bitwise... only on a Saturday night.

It just goes to show that sleep is very important for interviews!