如何在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
热门推荐
10 生日祝福语简短激励女生
11 送水杯祝福语女生简短
12 老婆生日祝福语短句简短
13 毕业结婚祝福语简短精辟
14 宝宝祝福语诗意简短 古文
15 简短新婚铺被子祝福语
16 送给姐姐简短的祝福语
17 新年祝福语大全简短老师
18 入学校简短祝福语