Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Kiểm tra số là power of 2 trong C#

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.

n2^n
01
12
24
38
416
532

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.