Give an array with 1 to N except 1 number. Find the missing number.
public static int FindMissingNumber(int[] a)
{
if (a == null || a.Length <= 1)
return 0;
int sum = 0;
for (int i = 0; i < a.Length; i++)
sum = sum ^ a[i] ^ (i+1);
return sum ^ (a.Length+1);
}
This solution is better:
a ={1,3} Missing 2
using XOR characteristic when XOR same= number it will become 0 : A XOR A = 0.
1st pass : 1 XOR 1 = 0
001 XOR 001 = 000
2nd pass : 0 XOR 3 XOR 2 = 1
000 XOR 011 XOR 010 = 001
Final : 1 XOR 3 = 2
001 XOR 011 = 010
* Avoid using n*(n+1)/2 – sum approach as this will introduce overflow for integer data type.
No comments:
Post a Comment