• RSS
  • Facebook
  • Twitter

Knowledge is Power.

  • Who you are ?

    Working on machines without understanding them ? Then you should be here..

  • Where you are ?

    Geographical location should not become a barrier to Share our knowledge.

  • What do you do ?

    Puzzles and Interview question are intended to be discussed here.

    Thursday, February 25, 2010

    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);
    }
    }

    0 comments:

    Post a Comment