- 39.6%
https://leetcode.com/problems/power-of-two/#/description
Given an integer, write a function to determine if it is a power of two.
方法一:
利用 n&(n-1)判断, 时间复杂度O(1)
值得关注的点, 1. 考虑n<=0的情况 2. n&(n-1)为0时是True,所以要加否定 3. 否定符号是 ! 不是 ~
1 | class Solution { |
or
1 | class Solution { |
方法二:
相除法,时间复杂度O(1)
1 | return n>0 && (1073741824 % n == 0); |
方法三:
迭代,时间复杂度 O(logn)
1 | if(n==0) return false; |
方法四:
递归,时间复杂度O(logn)
1 | return n>0 && (n==1 || (n%2==0 && isPowerOfTwo(n/2))); |
Python one line solution
1 | class Solution(object): |
参考资料: