【发布时间】:2015-08-31 17:15:18
【问题描述】:
我正在尝试解决这个 leetcode 问题: Given an array of numbers nums, in which exactly two elements appear only once and all the other elements appear exactly twice. Find the two elements that appear only once.
我知道标准的解决方案是计算 X^Y,并得到最低的不常见位,...
但我还有一个想法:
我可以通过 XOR 所有数字得到 X^Y;
xored = 0
for i in nums:
xored = xored^i
我也可以通过将数字的每个二进制位单独相加得到X+Y,模2。
# pseudo-code
bitvector = [0]* number of bits of integer
for n in numbers:
for bit in bitvector:
bitvector[i] += n[bit]
bitvector[i] = bitvector[i]%2
但我不知道如何获得 X 和 Y,使用 X+Y 和 X^Y,或者即使这是可能的。
你能帮忙吗?
【问题讨论】:
-
尝试解 X^Y = X+Y = 1111b 自己看看。
-
我多么愚蠢……
标签: algorithm bit-manipulation