In an integer array all numbers occur exactly twice except for a single number which occurs exactly once..give an O(n) algorithm to find the number occurring only once.
Ans: Do bitwise XOR of all numbers. The result will be the number that occurs only once. The result in each position is the different number if the two bits are different, and 0 if they are the same.
public class Xor
{
public static void main(String args[])
{
int[] arr= {1,1,2,2,3,4,4,5,5};
int xOR = arr[0] ;
for(int i =1 ;i< arr.length; i++)
{
xOR = xOR ^ arr[i];
System.out.println( arr[i] + " —- " + xOR);
}
System.out.println(xOR);
}
}



Working on machines without understanding them ? Then you should be here..
Geographical location should not become a barrier to Share our knowledge.
Puzzles and Interview question are intended to be discussed here.
0 comments:
Post a Comment