IsPowerOfTwo
Returns true if the given number is a power of 2, false otherwise.
- Use the bitwise binary AND operator (
&) to determine ifnis a power of2. - Additionally, check that
nis different from0.
public static partial class _30s
{
public static bool IsPowerOfTwo(ulong n)
{
return (n != 0) && ((n & (n - 1)) == 0);
}
}_30s.IsPowerOfTwo(0); // false
_30s.IsPowerOfTwo(1); // true
_30s.IsPowerOfTwo(8); // true