文章作者:Tyan
博客:noahsnail.com | CSDN | 简书
1. Description
2. Solution
- Version 1
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n == 0) {
return false;
}
while(n != 1) {
if(n % 2) {
return false;
}
n /= 2;
}
return true;
}
};
- Version 2
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n == 0) {
return false;
}
while(n != 1) {
if(n % 2) {
return false;
}
n >>= 1;
}
return true;
}
};
- Version 3
class Solution {
public:
bool isPowerOfTwo(int n) {
return n > 0 && !(n & (n - 1));
}
};