public static void main(String[] args) {
// TODO Auto-generated method stub
int arr[]={1,2,3,2,4,1,3};
//Following code is useful to find out the one non-repeated number in an array using XOR operator
int a=arr[0];
for(i=1;i<arr.length;i++)
{
a=a^arr[i]; /* At the end of the loop this XORing will be something like 1^2^3^2^4^1^3,
since XOR nullify equal number the non-repeated will be what is left*/
}
System.out.println(a);
}
}
Output- 4
Note- More about XOR can be found here
// XOR works on binary e.g. 6^5 is 110^101 and 1^0, 0^1 is equivalent to 1 hence the output will be 3 in this case. 1^1, 0^0 is equivalent to 0
Complexity- O(n)
// XOR works on binary e.g. 6^5 is 110^101 and 1^0, 0^1 is equivalent to 1 hence the output will be 3 in this case. 1^1, 0^0 is equivalent to 0
Complexity- O(n)
No comments:
Post a Comment