#include <stdio.h>
//数组中只有一个数字出现奇数次,找到它
//方法是直接异或数组全部成员
int FindOnlyOneNumOddTimes(const int *arr, unsigned int size)
{
int res = 0;
for (unsigned int count = 0; count < size; count++) {
res = res ^ arr[count];
}
return res;
}
//数组中只有两个数字出现奇数次,找到它们
//方法是直接异或数组全部成员得到res1,res1 == *num1 ^ *num2;
//任找到res1对应二进制中非0的一位,举例第m位为1
//将数组中第m位为1的数字全部异或,得到其中*num1
//*num2 = res1 ^ *num1
void FindOnlyTwoNumOddTimes(const int *arr, unsigned int size, int *num1, int *num2)
{
int res1 = 0;
for (unsigned int count = 0; count < size; count++) {
res1 ^= arr[count];
}
//找到最右边的1
int Position1 = res1 & (~res1 + 1);
for (unsigned int count = 0; count < size; count++) {
if ((arr[count] & Position1) == Position1) { //也可以写为if ((arr[count] & Position1) == 0) {
*num1 ^= arr[count];
}
}
*num2 = res1 ^ *num1;
return;
}
int main()
{
int arr1[] = {1, 1, 1, 2, 2, 3, 3, 3, 3};
printf("res = %d\n", FindOnlyOneNumOddTimes(arr1, sizeof(arr1)/sizeof(int)));
int arr2[] = {1, 1, 1, 2, 2, 3, 3, 3, 3, 4, 4, 5, 5, 6};
int res1 = 0;
int res2 = 0;
FindOnlyTwoNumOddTimes(arr2, sizeof(arr2)/sizeof(int), &res1, &res2);
printf("res1 = %d, res2 = %d\n", res1, res2);
return 0;
}