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)));
}
};