代码:
#include <iostream>
using namespace std;
int FindFirstIndexOf1(int number)
{
int index_bits = 0;
while (((number & 1) == 0) && (index_bits < 8 * sizeof(int)))
{
number = number >> 1;
index_bits++;
}
return index_bits;
}
//判断第index_bits为是否为1来分组
bool IsBit1(int number, int index_bits)
{
number = number >> index_bits;
return (number & 1);
}
void SearchNumbersOccursOneTimesInArray(int* pArray, int nLength, int* digit_1, int* digit_2 )
{
int result = 0;
if (pArray == nullptr || nLength < 2)
return;
for (int i = 0; i < nLength; i++)
{
result ^= pArray[i];
}
//从低位(最右边)开始查找,直到第n位为1停止
int first_index_of_1 = FindFirstIndexOf1(result);
*digit_1 = 0;
*digit_2 = 0;
for (int i = 0; i < nLength; i++)
{
if (IsBit1(pArray[i], first_index_of_1))
*digit_1 ^= pArray[i];
else
*digit_2 ^= pArray[i];
}
}
int main()
{
int pArray[] = { 2, 4, 3, 6, 3, 2, 5, 5 };
int nLength = sizeof(pArray) / sizeof(pArray[0]);
int digit_1 = 0;
int digit_2 = 0;
SearchNumbersOccursOneTimesInArray(pArray, nLength, &digit_1, &digit_2);
cout <<"只出现一次的数字有: "<< digit_1 << " " << digit_2 ;
cout << endl;
system("pause");
return 0;
}
测试: