Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 2^0 = 1
Example 2:
Input: 16
Output: true
Explanation: 2^4 = 16
Example 3:
Input: 218
Output: false
给定任意一个数,判断是不是2的幂:
1.不断模2
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n < 1:
return False
while n%2 == 0:
n /= 2
if n == 1:
return True
else:
return False
2.位运算:
2的幂次 x 表示成二进制一定是一个1后面若干个0,那么 x-1 一定是一个0后面若干个1,所以 x & (x-1) = 0 ,非2的幂无法得到0。即把x二进制的最后一个1去掉要等于0.
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and ((n & n-1) == 0)