如何在 C# 中检查某个数字是否为 2 的幂?
csharpserver side programmingprogramming更新于 2025/4/20 10:37:17
2 的幂是形式为 2n 的数字,其中 n 是整数
以数字 2 为底数、以整数 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

