Power of 2 là số dạng 2^n với n là integer. Kết quả của exponentiation với base 2 và exponent integer n.
| n | 2^n |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | 4 |
| 3 | 8 |
| 4 | 16 |
| 5 | 32 |
Cách 1: Bitwise operation (hiệu quả nhất)
class Program
{
static void Main()
{
Console.WriteLine(IsPowerOfTwo(9223372036854775809)); // False
Console.WriteLine(IsPowerOfTwo(4)); // True
Console.ReadLine();
}
static bool IsPowerOfTwo(ulong x)
{
return x > 0 && (x & (x - 1)) == 0;
}
}
Kết quả
False True
Cách 2: Loop division
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;
}
}
Kết quả
False True
Cách 1 dùng bitwise AND hiệu quả hơn: số power of 2 chỉ có 1 bit set, (x & (x-1)) == 0.