Finding the number missing in the sequence [duplicate]

馋奶兔 提交于 2019-12-03 00:22:46
Save

To answer your question , you just have to remember that

A XOR B = C => C XOR A = B

and it immediately follows that

(PARTIAL SUM) XOR (MISSING ELEMENT) = (TOTAL) => 
(TOTAL) XOR ( PATIAL SUM) = (MISSING ELEMNT)

To prove the first property, just write down the XOR truth table:

A B | A XOR B
0 0 | 0
0 1 | 1
1 0 | 1
1 1 | 0

Truth table in short : if both the bits are same, result of XOR is false, true otherwise.

On an unrelated note, this property of XOR makes it a nice candidate for simple ( but not trivial ) forms of encryption.

First of all, you can make your original method work even in the presence of integer overflow (as long as n fits in an int).

As to the XOR method, observe that R1 xor M == R2 (where M is the missing number). From this it follows that R1 xor M xor R2 == 0 and therefore M == R1 xor R2.

The XOR works because every time you XOR a bit with 1 you flip it, and every time you XOR a bit with 0 it stays the same. So the result of XORing all the data save the missing number gives you the 'negative' impression of XORing all the numbers. XORing these two together restores your lost number.

Let's just look at the XOR of the low order bit (LOB) to keep things simple. Let x be the missing integer.

Each integer in the list contributes a 1 or a zero the LOB of R1 (LOB(R1)).

Each integer in the range contributes a 1 or a zero to the LOB(R2).

Now suppose LOB(R1) == LOB(R2). Since R2 == R2 XOR x, this can only happen if LOB(x) == 0 == LOB(R1) XOR LOB(R2). (1 xor 1 = 0, 0 xor 0 = 0)

Or suppose (LOB(R1) == LOB(R2). This can only happen if LOB(x) == 1 == LOB(R1) XOR LOB(R2) (1 xor 0 = 1, 0 xor 1 = 1).

But what works for the low order bit works for all of them, because XOR is computed independently, bit by bit.

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!