判斷一個數是否是 2的冪次方:
思路:在二進制中 2^n形式如下
2^1=2:10 1:01
2^2=4:100 3:011
2^3=8: 1000 4:0111
2^4=16: 10000 5:01111
......
def isPowerOfTwo(n: int) -> bool:
if n==0:
return False
else:
return n&(n-1)==0
判斷一個數是否是 3的冪次方:
1. 在 int 類型範圍內,最大的一個3的冪數,一定是其他3的冪數的3^x 倍
2. 除3餘數==0, 且最後是 3/3==1,則爲3^x
INT_MAX = 0X7fffffff
INT_MIN = 0X80000000
import math
def power_3(n):
if n < 1: return False
import math
k = math.log(INT_MAX) // math.log(3)
big3 = math.pow(3, k)
return big3 % n == 0
def power_3(n):
if n<1: return False
else:
while n%3==0:
n = n//3
return n==1
判斷一個數是否是 4的冪次方:
1.
4^1: 4 100 0101
4^2: 16 10000 10101
4^3: 64 1000000 1010101010
2. 除4餘數==0, 且最後是 4/4==1,則爲4^x
def power_4(n):
if n==1:
return True
return n&(n-1) and n&0x55555555
def power_44(num):
if num < 1:
return False
else:
while num > 1:
num = num / 4
return num == 1