题目:
Given an integer n, return true if it is a power of two. Otherwise, return false.
An integer n is a power of two, if there exists an integer x such that n == 2^x.
给定一数,判断它是否是2的次方
这题有许多解法,我们先从最直观的开始
class Solution: def isPowerOfTwo(self, n: int) -> bool: if n<=0: #0和负数不在讨论範围 return False while n%2==0: n=n/2 return n==1
将一数不断除二直到不能整除
看最后结果是不是1,就知道该数是不是2的次方了
最后执行时间36ms(faster than 87.16%)
也有位元运算的解法
class Solution: def isPowerOfTwo(self, n: int) -> bool: count=0 while n>0: count=count+(n&1) n=n>>1 return count==1
我们可以发现2次方数在二进位表示时有共同的性质
1(1),10(2),100(4),1000(8),10000(16)......
那就是只有一位是1,其余都是0
所以我用191.的方法,用&1和>>数出该数二进位表示有几个1
若只有一个1,则该数是2的次方
最后执行时间27ms(faster than 98.57%)
不用迴圈的解法也是有的
import mathclass Solution: def isPowerOfTwo(self, n: int) -> bool: if n<=0: return False return (math.log10(n)/math.log10(2))%1==0
import math让我们可以用log函数
透过log的性质,我们可以知道log2(2的次方数)会是整数
且log10(n)/log10(2)=log2(n)
所以我们只要计算log10(n)/log10(2)再用%1判断是不是整数即可
最后执行时间33ms(faster than 92.75%)
那我们下题见