ยกกำลัง 2 คือตัวเลขของรูปแบบ 2n โดยที่ n เป็นจำนวนเต็ม
ผลลัพธ์ของการยกกำลังที่มีเลขสองเป็นฐานและจำนวนเต็ม n เป็นเลขชี้กำลัง
| n | 2n |
|---|---|
| 0 | 1 |
| 1 | 2 |
| 2 | 4 |
| 3 | 8 |
| 4 | 16 |
| 5 | 32 |
ตัวอย่างที่ 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;
}
} ผลลัพธ์
False True
ตัวอย่างที่ 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;
}
} ผลลัพธ์
False True