1.2的幂https://leetcode-cn.com/problems/power-of-two/
我的想法是不停地除以2,直到不能整除,最终为1则返回True,否则返回False
时间复杂度48%
1 class Solution: 2 def isPowerOfTwo(self, n: int) -> bool: 3 if n == 0: 4 return False 5 while n%2 == 0: 6 n /= 2.0 7 if n ==1: 8 return True 9 else: 10 return False
看官方解看到了“位运算“方法
2的幂在二进制中只有一个1,其余全是0
不是2的幂有一个以上的1
还学到了x&(-x)和x&(x-1),作用是只保留二进制最右边的1和去除二进制最右边的1。参考https://www.cnblogs.com/yzxag/p/12668034.html
1 class Solution(object): 2 def isPowerOfTwo(self, n): 3 if n == 0: 4 return False 5 return n & (-n) == n
1 class Solution(object): 2 def isPowerOfTwo(self, n): 3 if n == 0: 4 return False 5 return n & (n - 1) == 0
2.二叉搜索树的最近公共祖先https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-search-tree/
3.二叉树的最近公共祖先https://leetcode-cn.com/problems/lowest-common-ancestor-of-a-binary-tree/