Given an integer, write a function to determine if it is a power of two.
解题思路是2的幂次的特点(计算机是二进制的)。
判断一个数是否是2的幂,判断方法主要依据2的N次幂的特点:仅有首位为1,其余各位都为0.
class Solution
{
public:
bool isPowerOfTwo(int n)
{
return (n>0) && (!(n&(n-1)));
}
}
};
方法2:利用bitset<32>
class Solution
{
public:
bool isPowerOfTwo(int n)
{
if (n < 1) return false;
bitset<32> num(n);//转换成2进制
return num.count() == 1; //判断和是否是1
}
}
};