Given an integer, write a function to determine if it is a power of two.
Credits:
Special thanks to @jianchao.li.fighter for adding this problem and creating all test cases.
可以直接做:
class Solution {
public:
bool isPowerOfTwo(int n) {
if (n < 1) return false;
int res;
while (n>0)
{
res = n % 2;
if (res != 0)
{
if (n == 1)
return true;
else
return false;
}
n = n / 2;
}
}
};
也可以用位运算:
class Solution {
public:
bool isPowerOfTwo(int n) {
if (n < 1) return false;
return !(n&(n-1));
}
};