I have been given a list of n integers and these integers are in the range of 1 to n. There are no duplicates in list.But one of the integers is missing in the list.I have to find the missing integer.
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.
But the above method will fail if the sum of the numbers goes beyond maximum allowed integer.
So i searched for a second solution and i found a method as follows:
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.
How is this method working?..How is the XOR of R1 and R2 finds the missing integer in the above case?