Một lũy thừa của 2 là một số có dạng 2n với n là một số nguyên
Kết quả của phép lũy thừa với số hai là cơ số và số nguyên n là số mũ.
| n | 2n |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | 4 |
| 3 | 8 |
| 4 | 16 |
| 5 | 32 |
Ví dụ 1
Chương trình lớpclass 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;
}
} Đầu ra
False True
Ví dụ 2
Chương trình lớpclass 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;
}
} Đầu ra
False True