Code:
/* The number that appears only once in the array by rowandjj2014/8/14 */# include <stdio. h> # include <stdlib. h>/*** find the first digit in the binary value of the number xorval. **/INT firstbitis1 (INT xorval) {int Index = 0; while (xorval & 1) = 0) & (index <8 * sizeof (INT) // The operator priority cannot be exceeded, add a few more brackets {index ++; xorval = xorval> 1;} Return Index;}/*** to judge the second index bit in data (Binary) whether it is 1 */bool isbit1 (INT data, int index) {DATA = data> index; return data & 1 ;} /* ** data target array * Len array length * num1 a number that appears only once * Num2 another number that appears only once */bool findnumberappearonce (INT data [], int Len, int * num1, int * num2) {If (Data = NULL | Len <2) {return false;} int I; int xorval = 0; for (I = 0; I <Len; I ++) {xorval ^ = data [I];} int indexof1 = firstbitis1 (xorval); * num1 = * num2 = 0; // be sure to assign the value 0 for (I = 0; I <Len; I ++) {If (isbit1 (data [I], indexof1) {* num1 ^ = data [I];} else {* num2 ^ = data [I] ;}} return true ;}int main () {int N; while (scanf ("% d ",& N )! = EOF) {If (n <= 1) {continue;} int * arr = (int *) malloc (sizeof (INT) * n); If (! ARR) {exit (-1) ;}int I; for (I = 0; I <n; I ++) {scanf ("% d ", arr + I);} int num1, num2; If (findnumberappearonce (ARR, N, & num1, & num2) {If (num1 <num2) {printf ("% d \ n", num1, num2);} else {printf ("% d \ n", num2, num1 );}} free (ARR);} return 0 ;}
The above code can be further optimized, with the following nature:
A & (-a) retains the rightmost 1 in the binary form of A, and the other positions are 0. For example, 10 (1010) &-10 (0110) = 0010.Code:
/* The number that appears only once in the array */# include <stdio. h> # include <stdlib. h> bool findfirstappearoncenum (INT data [], int Len, int * num1, int * num2) {If (Data = NULL | Len <= 1) {return false ;} int I; int xorval = 0; for (I = 0; I <Len; I ++) {xorval ^ = data [I];} * num1 = * num2 = 0; // be sure to assign the value 0 int temp = xorval & (-xorval); // result: the rightmost 1 in xorval is reserved with the other bits 0for (I = 0; I <Len; I ++) // traverses the array and divides the array into two parts. Each part only has one digit and appears once {If (data [I] & temp) // One of the bits in temp is 1, and the other bits are 0. The preceding data [I] can separate two numbers that appear only once {* num1 ^ = data [I];} else {* num2 ^ = data [I];} return true;} int main () {int N; while (scanf ("% d", & N )! = EOF) {If (n <= 1) {continue;} int * arr = (int *) malloc (sizeof (INT) * n); If (! ARR) {exit (-1) ;}int I; for (I = 0; I <n; I ++) {scanf ("% d ", arr + I);} int num1, num2; If (findfirstappearoncenum (ARR, N, & num1, & num2) {If (num1 <num2) {printf ("% d \ n", num1, num2);} else {printf ("% d \ n", num2, num1 );}} free (ARR);} return 0 ;}