Python - 一道用按位异或解决的算法题

题目

已知一个数字数组。其中只有一个数字只出现1次,其他数字都出现2次。求只出现1次的数字。
例如,[1,1,2,3,2],只出现1次的数字是3。


思路:

异或的特点

  • 一个数与自身异或 => 清零
  • 一个数与零异或 => 这个数本身
  • 一个数1异或(相同位数的) => 这个数取反
  • 异或满足交换率和结合率
# 解答如下
from functools import reduce

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

# 验证
In [9]: get_one([1,1,2,3,2])
Out[9]: 3

猜你喜欢

转载自blog.csdn.net/weixin_39129504/article/details/85958500