Given an integer, write a function to determine if it is a power of two.
Example 1:
Input: 1
Output: true
Explanation: 20 = 1
Example 2:
Input: 16
Output: true
Explanation: 24 = 16
Example 3:
Input: 218
Output: false
思路:最开始自己想的很简单,就是一直除以2看是否最后等于1,或者调用python的bin()方法,看是不是二进制是不是1000...这种格式。两种思路代码如下:
class Solution:
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
while n>=2:
n = n/2
return n==1
class Solution:
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n>0 and bin(n).count('1')==1
同时看到用&方法做的,很佩服。这种方法思路是当n二进制是1000..时,(n-1)二进制是0111...,这时候用&操作才能为0
class Solution:
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n>0 and not(n & n-1)