【问题标题】:Is it possible to solve X and Y knowing X^Y and X+Y? [duplicate]知道 X^Y 和 X+Y 是否可以解决 X 和 Y? [复制]
【发布时间】: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,或者即使这是可能的。

你能帮忙吗?

【问题讨论】:

标签: algorithm bit-manipulation


【解决方案1】:

你不能。

按位异或只是没有进位的加法。您可以轻松构建反例:

 x   01   11
 y   10   00
xor  11   11

1 + 23 + 01 ^ 23 ^ 0 都有相同的结果。

【讨论】:

  • 2+2 == 4 + 02^2 != 4^0。加法是带进位的异或。
  • @amit 我的意思是,鉴于x + y == 3x ^ y == 3,不可能得到唯一的答案。
  • 我在挑剔解释中的措辞,而不是答案或示例的概念。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-05-06
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多