//给⼀组组数,仅仅有两个数仅仅出现了一次。其它全部数都是成对出现的,找出这两个数。
#include <stdio.h>
int find_one_pos(int num) //找一个为为1的位置
{
int n = 0;
while(num)
{
if (num & 1 == 1)
break;
else
{
n++;
num >>= 1;
}
}
return n;
}
void find_two_differ(int arr[], int len, int *num1, int *num2)
{
int i = 0;
int pos = 0;
int ret = 0;
*num1 = 0;
*num2 = 0;
for (i = 0; i < len; i++)
{
ret ^= arr[i];
}
pos = find_one_pos(ret);
for (i = 0; i < len; i++)
{
if (arr[i] & (1 << pos))
*num1 ^= arr[i];
else
*num2 ^= arr[i];
}
}
int main()
{
int arr[] = { 1, 2, 3, 4, 5, 1, 2, 3 };
int ret1 ;
int ret2 ;
find_two_differ(arr, sizeof(arr) / sizeof(arr[0]), &ret1, &ret2);
printf("num1=%d\nnum2=%d\n", ret1, ret2);
return 0;
}