The number appears only once in the array, and the number appears in the array
Description:In an integer array, all numbers except two appear twice. Write a program to find the numbers that appear only once.
Idea: first look at a simple instance. If you look for a number that appears only once in the array, the other number appears twice, the bitwise XOR of array elements can be used to obtain a number that appears only once in the array. In this question, if we look for two numbers that appear only once in an array, We need to divide the array into two sub-arrays, each of which contains only one number that appears once. The key lies in the criteria of grouping, while performing an exclusive or operation on all elements in the array produces an exclusive or of this number. If the result is not 0, one digit of a number is 1 and the other digit is 0, so that the result of an exclusive or is not 0. Therefore, the criteria for grouping are the first digit of 1 in the result that all elements in the array are exclusive or exclusive (assumed to be the nth digit ). Then, grouping is performed based on the number and elements in the array. The N-bit array element is divided into one group, and 0 is the other group. Perform all XOR in each sub-array to obtain the two numbers that appear only once in the array.
1 # include "stdafx. h "2 3 unsigned int FindFirstBitIs1 (int num); 4 bool IsBit1 (int num, unsigned int indexBit); 5 6 void findnumpearsaponce (int data [], int length, int * num1, int * num2) 7 {8 if (data = NULL | length <2) 9 return; 10 11 int resultExclusiveOR = 0; 12 for (int I = 0; I <length; ++ I) 13 resultExclusiveOR ^ = data [I]; 14 15 unsigned int indexOf1 = FindFirstBitIs1 (resultExclusiveOR ); 16 17 * num1 = * num2 = 0; 18 for (int j = 0; j <length; ++ j) 19 {20 if (IsBit1 (data [j], indexOf1) 21 * num1 ^ = data [j]; 22 else23 * num2 ^ = data [j]; 24} 25} 26 27 // find num. the first digit from the right is a 1-bit 28 unsigned int FindFirstBitIs1 (int num) 29 {30 int indexBit = 0; 31 while (num & 1) = 0) & (indexBit <8 * sizeof (int) 32 {33 num = num> 1; 34 + + indexBit; 35} 36 37 return indexBit; 38} 39 40 // determine whether the indexBit of the numeric num is 141 bool IsBit1 (int num, unsigned int indexBit) 42 {43 num = num> indexBit; 44 return (num & 1); 45} 46 47 int main () 48 {49 int data [] = {2, 4, 3, 6, 3, 2, 5, 5}; 50 int length = sizeof (data)/sizeof (int); 51 52 int result1, result2; 53 FindNumsAppearOnce (data, length, & result1, & result2); 54 55 printf ("% d \ n", result1, result2); 56 57 return 0; 58}