python中异或怎么算_python中的异或运算

leetcode上有这么一道题:【136. Single Number】

这个题是给出一个非空列表,里面的元素只有一个只出现了一次,其余都出现了两次,找出这个只出现了一次的元素。

这个题目很简单,写了一下直接提交:

from collections import Counter

class Solution:

def singleNumber(self, nums: List[int]) -> int:

counter = Counter(nums)

for i in counter:

if counter[i] == 1:

return i

翻了一下讨论,发现了一个很简单快速的方法:

class Solution:

def singleNumber(self, nums: List[int]) -> int:

return reduce(lambda x, y: x ^ y, nums)

查了一下异或运算,发现找到唯一值是异或运算在python中的主要用途之一。其原理是这样的:

a = 10

b = 76

print(a ^ b)

输出:70

当a,b都转换为二进制:

bin(a)

bin(b)

输出:0b1010与0b1001100

异或运算是将两个数相同位置(长度不一时要对齐)的数值,不同为1时,结果为1,否则为0 。比如:(0101) ^ (0011) = 0110。

这里a ^ b = 0b1000110,即70。

当两个数相同时,异或运算结果为0.