一个数组中只有两个数字是出现一次,其他所有数字都出现了两次。
编写一个函数找出这两个只出现一次的数字。
#include<stdio.h>
#include<string.h>
void search(int arr[], int len)
{
int* x = (int*)malloc(sizeof(int*));
int* y = (int*)malloc(sizeof(int*));
*x = 0;
*y = 0;
//全部进行按位与,根据相同数字按位与为零不同为一,因此结果一定不为零,且32个比特位上至少有一位为1。
int sum = arr[0];
int i = 0;
for (i = 0; i < len; i++)
{
sum ^= arr[i];
}
//找到最低位第一次出现1的位置,记为pos,因为此时的1一定是不同的两个数相应位置上的1和0亦或得到的。
int pos = 1;
{
while (sum & 1)
{
sum = sum >> 1;
pos = pos << 1;
}
}
//根据pos位置上的01值不同,将数组划分为两个数组,并各自亦或,得出每个数组出现一次的数字
i = 0;
for (i = 0; i < len; i++)
{
if (arr[i] & pos)
{
*x ^= arr[i];
}
else
{
*y ^= arr[i];
}
}
printf("%d %d", *x, *y);
}
int main()
{
int arr[] = { 1,2,3,4,5,6,1,7,2,3,4,5 };
int len = sizeof(arr) / sizeof(arr[0]);
search(arr, len);
return 0;
}