C language to find a single dog

Given a set of arrays, eg: {1, 2, 3, 4, 5, 6, 1, 2, 3, 4}, please find out the two numbers 5 and 7.
The idea of ​​solving the problem, first of all, we can group them. Note that 5 and 7 must be divided into different groups, so how to achieve it? We can consider using XOR operation, we can choose to let 1 4 1 4 5 a group, 2 3 2 3 6 a group, after two groups of XOR get the binary representation bits of 5 and 6 respectively, we can observe that 5 and The binary numbers of 6 are 101 and 110 respectively. We can see that their last digits are different, so we can look for them according to this idea.
1. First, all the elements in the array can be XORed, then the result obtained at this time is the XOR result of 5 and 6, because the same element will be 0 after XOR for (i = 0; i
< k; i++)
{ ret = arr[i] ^ ret;//ret stores the XOR result of 5 and 6

}

2. We let ret move backward by i bits until we find the position of I when the & operation with ret is 1.
Find and record.
3. Let the elements in the array perform the & operation with 1. If it is equal to 1, then divide it into the first group, and then let the first group perform an XOR operation. At this time, the value of 5 can be obtained. Similarly, If it is not equal to 1, it is divided into the second group. At this time, the result of 6 is also obtained.
The source code is as follows:
void find(int arr[], int k)
{ int i = 0; int ret = 0; for (i = 0; i < k; i++) { ret = arr [i] ^ ret;//ret stores the XOR result of 5 and 6




	}
	int pos = 0;//记录ret移动了多少位为1
	for (i = 0; i < 32; i++)
	{
	
		if (((ret >> i) & 1) == 1)
		{
			pos = i;//如果ret进行了i次位移与1进行与运算为1,那么跳出循环,并记录i的位置
			break;
		}
	}
	int x = 0;//用来接收位移pos位后和1进行与运算等于1的所有结果
	int y = 0;
	for (i = 0; i < k; i++)
	{

		if (((arr[i] >> pos) & 1) == 1)//此时让数组中的元素也进行位移pos位操作,
		{
			x = x ^ arr[i];//没得到一次x的结果就进行异或运算,这样元素值相同的元素会变为0
		}
		else
		{
			y = y ^ arr[i];
		}


	}
	printf("%d %d", x, y);

}


int main()
{
	int arr[] = { 1, 2,3,4,5,8,1,2,3,4};
	int sz = sizeof(arr) / sizeof(arr[0]);
	find(arr, sz);

	return 0;
}

Guess you like

Origin blog.csdn.net/Kirihara_Yukiho/article/details/123384769