//一个整型数组里除了两个数字之外,其他的数字都出现了两次。请写程序找出这两个只出现
//一次的数字。要求时间复杂度是O(n),空间复杂度是O(1).
#include "iostream"
using namespace std;
//以异或后第x位是否为1分为两组,分别找出只出现一次的数
void FindNumsAppearOnce(int a[], int n)
{
if (a == NULL || n <= 1)
return;
int res = 0;
for (int i = 0; i < n; ++i)
res ^= a[i];
int firstOf1Bit = 1;
while (true)
{
if ((res >> firstOf1Bit) & 0x01)
break;
firstOf1Bit++;
}
int result1 = 0;
int result2 = 0;
for (int i = 0; i < n; i++)
{
if ((a[i] >> firstOf1Bit) & 0x01)
result1 ^= a[i];
else
result2 ^= a[i];
}
cout << result1 << " " << result2 << endl;
}
void test()
{
int a[] = { 1, 3, 2, 2 };
FindNumsAppearOnce(a, sizeof(a) / sizeof(int));
}
int main()
{
test();
return 0;
}