0. 总结
位运算常见的操作:异或、统计二进制中1的个数。
1. 汉明距离
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
思路
先异或, 再使用bin函数统计1的个数
bin(xor).count('1')
先异或, 再通过xor与xor-1取&, 计算1的位数
"""
xor = x ^ y
dist = 0
while xor:
dist += 1
xor = xor & (xor - 1)
return dist
2. 只出现一次的数字
class Solution(object):
def singleNumber(self, nums):
"""
:type nums: List[int]
:rtype: int
笨办法:
1. 使用Counter
[val for val, freq in Counter(nums).items() if freq == 1][0]
2. 先排序,再左右邻居跟自己不等,就输出;
聪明解法:
异或运算,对整个数组异或,相同元素抵消,只留下频次为1的一个元素
https://leetcode-cn.com/problems/single-number/comments/42235
"""
r = 0
for num in nums:
r = r ^ num
return r
3. 比特位计数
class Solution(object):
def countBits(self, num):
"""
:type num: int
:rtype: List[int]
思路
计算一个整数的二进制形式的1的位数 我们在海明距离题目中已经实现过
这里不过是在上面封装了一个数组
"""
def count_one(x):
cnt = 0
while x:
cnt += 1
x = x & (x - 1)
return cnt
result = [count_one(i) for i in range(num+1)]
# result = [bin(i).count('1') for i in range(num+1)] # 使用内置bin函数
return result