Agree on needing comments.
My C++ is a bit rusty, but I think the code is in fact checking if the number is divisible by 2 (i.e. n % 2 == 0).
I think it's using the bitwise and operator (single &) to AND each bit in n and (n-1) and then checking if the least significant bit is 1 or 0. The code would need to shift (<< or >>) to check if the number were a power of 2.
I thought there was another bitwise NOT operator, not the !, but I think, and this is the part I'm hazy on after getting home, that the ! applied to an int is intended to flip each bit. Here's why:
------------
n = 6 = 110
n-1 = 5 = 101
n & (n-1) = 110 & 101 = 100
!(110) = 001 => true
------------
n = 5 = 101
n-1 = 100
n & (n-1) = 101 & 100 = 101
!(101) = 010 => false only if the least significant bit is used for logic decisions... this seems non-portable for some reason, just like using the ! as a bitwise NOT. It may actually be that ! only looks at the least significant bit, but I can't find c++ docs to say one way or another.
Whatever the code actually does, this is exactly the kind of example to use as a poster child for adding just a few comments.
My C++ is a bit rusty, but I think the code is in fact checking if the number is divisible by 2 (i.e. n % 2 == 0).
I think it's using the bitwise and operator (single &) to AND each bit in n and (n-1) and then checking if the least significant bit is 1 or 0. The code would need to shift (<< or >>) to check if the number were a power of 2.
I thought there was another bitwise NOT operator, not the !, but I think, and this is the part I'm hazy on after getting home, that the ! applied to an int is intended to flip each bit. Here's why:
------------
n = 6 = 110
n-1 = 5 = 101
n & (n-1) = 110 & 101 = 100
!(110) = 001 => true
------------
n = 5 = 101
n-1 = 100
n & (n-1) = 101 & 100 = 101
!(101) = 010 => false only if the least significant bit is used for logic decisions... this seems non-portable for some reason, just like using the ! as a bitwise NOT. It may actually be that ! only looks at the least significant bit, but I can't find c++ docs to say one way or another.
Whatever the code actually does, this is exactly the kind of example to use as a poster child for adding just a few comments.