Given an integer, write a function to determine if it is a power of two.
2的幂的二进制表示中,必然只有一个“1”,且不可能为负数。
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<0)
{//若为负数则直接返回
return false;
}
int num=0;
while(n)
{//统计1的个数
n=n&(n-1);
num++;
}
if(num==1)
return true;
return false;
}
};版权声明:本文为博主原创文章,未经博主允许不得转载。
原文:http://blog.csdn.net/walker19900515/article/details/46786173