我得到了一个包含n个整数的列表,这些整数的范围是1到n。列表中没有重复的数字。但是列表中缺失了一个整数。我需要找出这个缺失的整数。
Example: If n=8
I/P [7,2,6,5,3,1,8]
O/P 4
I am using a simple concept to find the missing number which is to get the
sum of numbers
total = n*(n+1)/2
And then Subtract all the numbers from sum.
然而,如果数字总和超过允许的最大整数,则上述方法将失败。
因此,我搜索了第二种解决方案,并找到了以下方法:
1) XOR all the elements present in arr[], let the result of XOR be R1.
2) XOR all numbers from 1 to n, let XOR be R2.
3) XOR of R1 and R2 gives the missing number.
这种方法是如何工作的?..在上述情况下,R1和R2的异或如何找到缺失的整数?
[n - (n-1)]
不等于 1。 - Geeky Guy