Given an integer, write a function to determine if it is a power of two.
思路:
如果一个数是2的Power,那么该数的二进制串中只有一位为1,其余都为0。执行一次n & (n - 1)可消除最低位的一个1,若消除后为0,则说明该数是2的Power(n == 0 || n == -2147483648 时要特殊考虑)。
C++:
class Solution {
public:
bool isPowerOfTwo(int n) {
if(n == || n == -)
return false; n = n & (n - ); if(n == )
return true;
else
return false;
}
};
Python:
class Solution:
# @param {integer} n
# @return {boolean}
def isPowerOfTwo(self, n):
if n == 0 or n == -2147483648:
return False n = n & (n - 1) if n == 0:
return True
else:
return False