判断是不是2的幂次,有好几种方法,比如以二为底取log,比如依次除以二看能不能除到结果为1为止,比如n&(n-1)==0。
(1)C语言实现
bool isPowerOfTwo(int n) {
if(n>0 && (n&(n-1)==0))
return true;
else
return false;
}
/*解法二
bool isPowerOfTwo(int n) {
if(n<=0)
return false;
while(n%2==0){
n /= 2;
}
return n==1;
}*/
(2)C++实现
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0)
return false;
double n1 = log10(n)/log10(2);
return (n1-(int)n1)==0;
}
};
/*解法二
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0)
return false;
while(n%2==0){
n /=2;
}
return n==1;
}
};
*/
/*解法三
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n<=0)
return false;
return (n&(n-1))==0;
}
};
*/
(3)java实现
public class Solution {
public boolean isPowerOfTwo(int n) {
if(n>0 && (n&(n-1)==0))
return true;
else
return false;
}
}