Title Description: to an array, there are two numbers appear only once, the other number appears two times, please find out these two numbers;
Example: Input 2 4 2 7 4 9
Output 7 9
Idea: Suppose to find out the two numbers for x, y put all the number of different or, the result is x and y xor value, then certainly not 0, then the value of the binary at least one is 1, that is, x and y binary on this one must be a 0, a 1, then you can divide the array into two arrays according to this bit, X and y are in different arrays, and the next value that is directly different or out of each array is the result;
The code is as Follows:
#include <iostream>#include<cstdio>using namespacestd;intnum1,num2;intSinglenumber (intnums[],intLength) {num1=num2=0; if(length<2)return-1; intRe=0; for(intI=0; i<length;i++) Re^=nums[i]; intInd=0; while((re&1)==0&& (ind<8*sizeof(int)) {re=re>>1; ++ind; } for(intj=0; j<length;++J) {intt= (nums[j]>>ind) &1; if(t) num1^=nums[j]; Elsenum2^=nums[j]; }}intmain () {intnums[ -]={2,4,2,7,4,9}; Singlenumber (nums,6); cout<<num1<<" "<<num2<<endl; return 0;}
Interview Questions---find Two occurrences of the number in the array