python leetcode 日记--231. Power of Two

时间:2021-10-28 09:12:43

题目:

Given an integer, write a function to determine if it is a power of two.

class Solution(object):
def isPowerOfTwo(self, n):
#
"""
:type n: int
:rtype: bool
"""

方法:分析2的幂次方的特点,发现2的任意次方的数,化成二进制时只有首位为1其余位为0,因此我的解决方法如下:

class Solution(object):
def isPowerOfTwo(self, n):
return False if n<0 else (True if bin(n).count('')==1 else False)

bin函数能将一个给定的数化成二进制,返回为字符串形式,因此只要检查bin的返回值中是否含有一个‘1’即可。

将上面的一行代码分解来看就是

class Solution(object):
def isPowerOfTwo(self, n):
if n<0:
return False
return True if bin(n).count('')==1 else False

之后看其中其他解决方法主要为n&(n-1)==0,这个方法也是利用了2的幂次方的特点,n若是2的幂次方,那么(n-1)的二进制数只有最高位为0,其余位全为1,因此让n&(n-1)按位与,如果等于0,则说明n是2的幂次方