题目
一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现一次的数字。
思路
所有的数字进行亦或运算,得到的数字最后一个不为0的位作为区分条件。
代码
# -*- coding:utf-8 -*-
class Solution:
# 返回[a,b] 其中ab是出现一次的两个数字
def FindNumsAppearOnce(self, array):
# write code here
num = 0
for i in array:
num ^= i
diff = 1
while not diff & num:
diff <<= 1
num1 = 0; num2 = 0
for i in array:
if i & diff: num1 ^= i
else: num2 ^= i
return [num1, num2]