直接在内存中进行二进制位运算操作,不需要转化成十进制,速度快。
Leetcode191
输出无符号整数的二进制形式中的1的个数
可以采用位运算操作,x&(x-1)可表示将x的最后一位1清0
class Solution(object):
def hammingWeight(self, n):
"""
:type n: int
:rtype: int
"""
count = 0
while n:
if n % 2:
count += 1
n = n >> 1
return count
def hammingWeight1(self, n):
count = 0
while n != 0:
n &= n - 1
count +=1
return count
Leetcode 52
N皇后问题
class Solution(object):
def totalNQueens(self, n):
"""
:type n: int
:rtype: int
"""
if n < 1: return []
self.count = 0
self.dfs_(n, 0, 0, 0, 0)
return self.count
def dfs_(self, n, row, col, pie, na):
if row >= n:
self.count += 1
return
bit = (~(col | pie | na)) & ((1 << n) - 1)
while bit:
p = bit & -bit
self.dfs_(n, row + 1, col | p, (pie | p) << 1, (na | p) >> 1)
bit = bit & (bit - 1)