* 问题:存在一组数
* 问题 a):这组数中只存在一个数出现的次数是奇数,其他数都是偶数,找到这个奇数
* 问题 b):这组数中存在两个数出现的次数是奇数,其他数都是偶数,找到这两个奇数
* 要求:时间复杂度O(N),空间复杂度O(1)
#include<iostream>
using namespace std;
void findOddNumber1(int arr[],int length);
void findOddNumber2(int arr[], int length);
int main()
{
int a1[] = { 1,8,1,1,2,6,2,2,3,3,2,3,4,5,6,3,7,5,7,8,1};
findOddNumber1(a1,sizeof(a1)/sizeof(a1[0]));
int a2[] = { 1,1,1,1,2,2,2,2,3,3,3,3,4,5,6,7,8,5,6,7,8,6 };
findOddNumber2(a2, sizeof(a2) / sizeof(a2[0]));
return 0;
}
void findOddNumber1(int arr[], int length)
{
int eor = 0;
for (int i = 0; i < length; i++)
{
eor ^= arr[i];
}
cout << "问题a的答案是:"<< eor << endl;
}
void findOddNumber2(int arr[], int length)
{
int eor = 0;
for (int i = 0; i < length; i++)
{
eor ^= arr[i];
}
int rightOne = eor & (~eor + 1);
int eor_2 = 0,eor_3 = 0;
for (int i = 0; i < length; i++)
{
if((arr[i] & rightOne) == rightOne)
{
eor_2 ^= arr[i];
}
}
eor_3 = eor ^ eor_2;
cout << "问题b的答案是:"<< eor_2 << "\t" << eor_3 << endl;
}