Given an integer array nums, exactly two elements appear only once, and all other elements appear twice. Find the two elements that only appear once.
Idea: After all the numbers are XORed; numN = the XOR of two target numbers (two identical numbers XOR result is 0, 0 and any number XOR result is that The number itself), find the bit with the digit of 1 in newN after the XOR (the two target numbers on this bit must be one of 1 and the other 0), and divide the bit of 1 in the array into a group XOR, 0 is divided into a group of XOR, then two target numbers are obtained.
int* singleNumber(int* nums, int numsSize)
{ int newN=0; //Exclusive OR of all numbers for(int i=0;i<numsSize;++i) { newN^=nums[i]; } int m=0; //Find the bit where the binary number is 1 after XOR while(m<32) { if(newN & (1<<m))//ret and 0 phase and 0 break; else ++m ; } //Separate int x1=0,x2=0; for(int i=0;i<numsSize;i++) { if(nums[i]&(1<<m)) { x1^=nums[i] ; } else { x2^=nums[i]; } } int retArr=(int )malloc(sizeof(int)*2); retArr[0]=x1; retArr[1]=x2;
return retArr;
}