I realize that this is an old question, but I though I'd provide my approach anyway.
What you really want to do, is count the number of active or set bits, as a power of two is always represented as a single bit.
Now, I'm not much for javascript, so this is semi pseudo/c code, but I do believe the operators are more or less the same.
bool isPowerOf2( uint64_t b )
{
b = ((b >> 1) & 0x5555555555555555) + (b & 0x5555555555555555);
b = ((b >> 2) & 0x3333333333333333) + (b & 0x3333333333333333);
b = ((b >> 4) & 0x0f0f0f0f0f0f0f0f) + (b & 0x0f0f0f0f0f0f0f0f);
b = ((b >> 8) & 0x00ff00ff00ff00ff) + (b & 0x00ff00ff00ff00ff);
b = ((b >> 16) & 0x0000ffff0000ffff) + (b & 0x0000ffff0000ffff);
b = ((b >> 32) & 0x00000000ffffffff) + (b & 0x00000000ffffffff);
return (b==1);
}
Now this is able to handle 64 bit, but if you only need 32 or less, it can be adapted accordingly.
It may look complicated, but it really isn't.
What you do is separate the bit up in to pairs and add them. First you add bit 0 with bit 1, bit 2 with bit 3, etc. Then you do the same again, adding bit 0-1 with 2-3, 4-5 with6-7, and so on.
With the exception of some architecture depended instructions, like GCCs __builin_popcount, I know of no way that is more efficient, but then again, if you're coding in javascript, that is probably not a priority, and you may want to use another method. Just know that what you really want to do, is count bits.
return n & (n - 1) === 0
. Try to understand how it works. \$\endgroup\$Number.MAX_SAFE_INTEGER
(2^53 - 1) because those operations coerce inputs to 32-bit signed values. \$\endgroup\$Math
library? \$\endgroup\$