如何在C#中检查数字是否为2的幂?
2的幂是2n形式的数字,其中n是整数
以2为底数,整数n为指数的求幂结果。
例子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