231. Power of Two
Given an integer, write a function to determine if it is a power of two.
Link:
https://leetcode.com/problems/power-of-two/
Analysis:
方法还是有几种的,比如:除2法,log法,列举法等等。跟326. Power of Three这道题差不多。
初次之外还有另外一种方法,n是2的次方,它的形式一定为1000….(1后若干个0),这样n&(n-1)=0,详见代码。
Source Code(C++):
#include <iostream>
using namespace std;
class Solution {
public:
bool isPowerOfTwo(int n) {
if (n<1) {
return false;
}
else {
if (n&(n-1)) {
return false;
}
else {
return true;
}
}
}
};
int main() {
Solution sol;
cout << sol.isPowerOfTwo(27);
return 0;
}