Simple solution in java


  • 0
    C
    //Solutions is based on the below website  
    //http://www.codinghelmet.com/?path=exercises/two-numbers-appearing-once-in-array  
       
    
         public int[] singleNumber(int[] nums) {
                
                int xorOfArray = 0; //Used to filter divide the array into two group...
                
                for(int i = 0 ; i < nums.length ; i++)
                {
                      xorOfArray = xorOfArray ^ nums[i];
                }
                
                System.out.println("Xor of array is "+xorOfArray);
                
                int mask = xorOfArray & ~(xorOfArray - 1); // Unset all the bits except right most...
                
                int xorOfZeroBit = 0,xorOfOneBit = 0;
                
                for(int i = 0 ; i < nums.length ; i++)
                {
                    if( ( nums[i] & mask ) == 0 ) 
                    {
                        xorOfZeroBit = xorOfZeroBit ^ nums[i];
                    }
                    else
                    {
                        xorOfOneBit = xorOfOneBit ^ nums[i];
                    }
                }
                
                int result[] = new int[]{xorOfOneBit,xorOfZeroBit};
                return result;
            }
        }

Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.