您的位置:首页 > 其它

LeetCode 231 Power of Two(三解)

2016-03-28 23:37 190 查看
231.
Power of Two

Given an integer, write a function to determine if it is a power of two.

我的方法是暴力求解,循环让1一直乘以2,如果结果等于n,且n大于0则输出true。这是最容易想到的方法

class Solution {
public:
bool isPowerOfTwo(int n) {
int result=1;
for(int i=0;i!=1000;i++)
{
if(result==n &&n>0)
{
return true;
}
result*=2;
}
return false;
}
};搜索网上的资料发现更巧妙的方法,利用到了十六进制的特点(2的N次幂的特点:仅有首位为1,其余各位都为0.)
class Solution {
public:
bool isPowerOfTwo(int n) {
int cnt = 0;
while (n > 0) {
cnt += (n & 1);
n >>= 1;
}
return cnt == 1;
}
};

或者
class Solution {
public:
bool isPowerOfTwo(int n) {
return (n > 0) && (!(n & (n - 1)));
}
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: