知道 X^Y 和 X+Y 是否可以求解 X 和 Y?

Is it possible to solve X and Y knowing X^Y and X+Y?

我正在尝试解决这个 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,并获得最低的不常见位,...

不过我还有一个想法:

我可以对所有数字进行异或得到X^Y;

xored = 0
for i in nums:
   xored  = xored^i

我也可以通过将数字的每个二进制位单独相加并取模 2 来得到 X+Y。

# 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   01   11
 y   10   00
xor  11   11

1 + 23 + 01 ^ 23 ^ 0的结果都是一样的。