数组n中只有两个数出现了奇数次,其他数均出现了偶数次
利用异或运算:A^B^A = B^A^A = B ; A^A = 0 ; A^0 = A
#include <iostream>
using namespace std;
void fun(int * array,int len)
{
if (array == nullptr || len<4)
{
return;
}
int S(0), k(0), a(0);
for (auto i = 0; i < len;++i)
{
S = S^array[i];
}
while (!((S>>k)&1))
{
++k;
}
for (auto i = 0; i < len;++i)
{
if ((array[i]>>k)&1)
{
a = a^ array[i];
}
}
cout << a << " ;" << (S^a) << endl;
}
int main()
{
int a[7]{-1, -1, 3, 4,3, 7};
fun(a, 7);
return 0;
}