A power of 2 is a number of the form 2n where n is an integer
The result of exponentiation with number two as the base and integer n as the exponent.
| n | 2n |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | 4 |
| 3 | 8 |
| 4 | 16 |
| 5 | 32 |
Example 1
class Program {
static void Main() {
Console.WriteLine(IsPowerOfTwo(9223372036854775809));
Console.WriteLine(IsPowerOfTwo(4));
Console.ReadLine();
}
static bool IsPowerOfTwo(ulong x) {
return x > 0 && (x & (x - 1)) == 0;
}
}Output
False True
Example 2
class Program {
static void Main() {
Console.WriteLine(IsPowerOfTwo(9223372036854775809));
Console.WriteLine(IsPowerOfTwo(4));
Console.ReadLine();
}
static bool IsPowerOfTwo(ulong n) {
if (n == 0)
return false;
while (n != 1) {
if (n % 2 != 0)
return false;
n = n / 2;
}
return true;
}
}Output
False True