如何检查一个数字是否为2的幂
ulong
private bool IsPowerOfTwo(ulong number){ if (number == 0) return false; for (ulong power = 1; power > 0; power = power << 1) { // This for loop used shifting for powers of 2, meaning // that the value will become 0 after the last shift // (from binary 1000...0000 to 0000...0000) then, the 'for' // loop will break out. if (power == number) return true; if (power > number) return false; } return false;}
log2 x
Math.Log
double
private bool IsPowerOfTwo_2(ulong number){ double log = Math.Log(number, 2); double pow = Math.Pow(2, Math.Round(log)); return pow == number;}
true
9223372036854775809
.
墨色风雨