题目描述:给定一个整数 n ,判断其是否为 2的次方。
解题思路:首先想到的是将 n 转换成二进制,看里面 1 的个数是否为 1,若为 1,说明是 2 的次方。
C++实现如下:
class Solution {
public:
bool isPowerOfTwo(int n)
{
int count = 0;
while(n > 0)
{
count ++;
n = n & (n-1);
}
return count==1;
}
};