Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> C#

ตรวจสอบว่าเลขเป็น Power of 2 ใน C#

Power of 2 = 2ⁿ (n = Integer ≥ 0) → 1, 2, 4, 8, 16, 32, 64...

ใน Binary มีแค่ Bit เดียวที่เป็น 1: 1 (1), 10 (2), 100 (4), 1000 (8)...

วิธี 1: Bitwise Operation (Fastest)

bool IsPowerOfTwo(ulong x)
{
    return x > 0 && (x & (x - 1)) == 0;
}

Logic: x & (x-1) จะเป็น 0 ก็ต่อเมื่อ x มี Bit 1 อยู่ตัวเดียว

วิธี 2: Loop Division

bool IsPowerOfTwo(ulong n)
{
    if (n == 0) return false;
    while (n != 1)
    {
        if (n % 2 != 0) return false;
        n /= 2;
    }
    return true;
}

Test Cases

IsPowerOfTwo(4)      // True
IsPowerOfTwo(8)      // True
IsPowerOfTwo(9223372036854775809) // False (2^63 + 1)
IsPowerOfTwo(0)      // False

Benchmark

  • Bitwise: O(1) เร็วที่สุด
  • Loop: O(log n) ช้ากว่า แต่เข้าใจง่าย