231. Power of Two(另一种特殊求法)
Given an integer, write a function to determine if it is a power of two.
这里个人想到三种解法
第一种
一种是求这个数的以2为底的对数,然后取整数部分,作2的乘方,看是否相等
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return n > 0 and 2 ** round(math.log(n, 2)) == n
第二种
另一种是有专有代码写法,直接求出比这个数大的2次幂,然后比较是否相等
个人觉得这个效率高
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
if n <= 0:
return n > 0
x = n
--x
x |= x >> 1
x |= x >> 2
x |= x >> 4
x |= x >> 8
x |= x >> 16
return (x+1) >> 1 == n
**
先求出比n大的2的幂中最小的数(譬如3就是4,1就是2,然后除以2看是否跟n相等)**
第三种
这道题还有一个技巧,如果一个数是2的次方数的话,根据上面分析,那么它的二进数必然是最高位为1,其它都为0,那么如果此时我们减1的话,则最高位会降一位,其余为0的位现在都为变为1,那么我们把两数相与,就会得到0,用这个性质也能来解题,而且只需一行代码就可以搞定
class Solution(object):
def isPowerOfTwo(self, n):
"""
:type n: int
:rtype: bool
"""
return (n > 0) and ((n & (n - 1))) == 0
献上最后一种的go语言写法
func isPowerOfTwo(n int) bool {
return (n > 0) && (n & (n - 1)) == 0
}