位运算
位运算题目1—leetcode191:
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
count=0
while n:
count+=1
n=n&(n-1) ## 提出当前的最低位的1
return count
- 第二种方法
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
mask=1
count=0
for i in range(32):
if n & mask:## 如果这位是1的话
count+=1
mask=mask<<1
return count
位运算题目2—231
class Solution:
def isPowerOfTwo(self, n: int) -> bool:
return n!=0 and (not n&(n-1))
位运算 leetcode338
解题思路 在计算第i位的时候 第i&(i-1)位已经算出来了 他们之间正好相差1个1
class Solution:
def countBits(self, num: int) -> List[int]:
re=[0 for i in range(num+1)]
for i in range(num):
i=i+1
re[i]+=re[i&(i-1)]+1
return re
发现用map的速度更对 快在 插入部分吧
class Solution:
def countBits(self, num: int) -> List[int]:
re={}
for i in range(num+1):
if i ==0:
re[i]=0
else:
re[i]=re[i&(i-1)]+1
return list(re.values())
题目 leetcode 52_使用位运算解决N皇后解法数量问题
class Solution:
def totalNQueens(self, n: int) -> int:
if n<1:
return []
self.result=0
self._dfs(n,0,0,0,0)
return self.result
def _dfs(self,n,row,col,pie,na):
if row>=n:
self.result+=1
return
space=(~( pie | na |col))&((1<<n)-1) ##可以空间 0101 0是可用 1是不可用 取反去高位 表达成数
while space:
bit = space & -space ##取最低位的1
self._dfs(n,row+1,col|bit,(pie|bit)<<1,(na|bit)>>1) ## 进入dfs
space=space&(space-1)## 去掉最低的那个1