bits 套路 代码

power of 4 - 变态的一道题要求你知道num 只有一个1 表示powerof2 并且之前的bit数量必须是偶数

套路

power of 2 - x&(x-1)==0 where x>0

查看多少个1

n == (n&-n) - 利用2’s complement, negating的话可以查看原来的数究竟有没有1

** 前提是n>0

let’s do the 套路

代码

1
2
3
4
5
6
7
8
9
10
11
12
def poweroffour(n):
if n==1: return True
count = 0
if (n & (n-1))==0: #if power of 2
while n>1:
n>>=1 #divided by 2 or shift right
count+=1
if count%2==0:
return True
return False

power of 3 - find max integer of 3’s power and modulo it

len(bin(3**x))-2 < 32, x==19