题目来源【Leetcode】
Given an integer, write a function to determine if it is a power of two.
判断一个数是否为2的N次方
方法一:取对数
class Solution {
public:
bool isPowerOfTwo(int n) {
double i = log10(n)/log10(2);
return (i-(int)i) == 0;
}
};
方法二:用二进制的特点
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && !(n&(n-1));
}
};
方法三:用最大的2进制数
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && 4294967296%n == 0;
}
};