leetcode-231-2的幂
作者:互联网
题目描述:
第一次提交:
class Solution: def isPowerOfTwo(self, n: int) -> bool: if n==0:return False if n==1: return True s = str(bin(n))[3:] for i in s: if i == '1': return False return True
优化:
class Solution: def isPowerOfTwo(self, n: int) -> bool: return n > 0 and bin(n).count("1") == 1
方法二:O(1)
class Solution: def isPowerOfTwo(self, n: int) -> bool: return n > 0 and n & (n - 1) == 0
方法三:O(logn)
class Solution: def isPowerOfTwo(self, n: int) -> bool: if n == 0: return False while n % 2 == 0: n //= 2 return n == 1
标签:return,int,self,Solution,231,bool,isPowerOfTwo,leetcode 来源: https://www.cnblogs.com/oldby/p/11625041.html