https://leetcode.com/problems/power-of-two/
Given an integer, write a function to determine if it is a power of two.
比较直接的办法
public bool IsPowerOfTwo(int n)
{
if (n < 1)
return false;
while (n!=1)
{
if (n % 2 == 1)
return false;
n >>= 1;
}
return true;
}
技巧:如果一个整数是2的幂,那么它的二进制形式最高位为1,其余各位为0
public bool IsPowerOfTwo(int n)
{
return n > 0 && (n & (n - 1)) == 0;
}