//問題描述:數組中只出現一次的數有兩個,其他都是成對出現的,請找出這兩個數只出現一次的數
實現的代碼:
size_t FindFirstBitIs1(size_t Num) //找出某個數(二進制串)從右往左的第一個 1 (例如: 14 -- 1110 返回 2 -- 10)
{
int IndexBit = 1;
for (int i = 0; i < 32; ++i)
{
if (Num & IndexBit)
return IndexBit;
IndexBit <<= 1;
}
}
void FindNumsAppearOnce(int* arr, int lenth,int* Num1,int* Num2) //主要思路是兩個數相等異或結果為零
{
assert(arr);
if (lenth < 2)
{
cout << "輸入有誤!" << endl;
return;
}
size_t ResultExclusiveOr = 0;
for (int i = 0; i < lenth; ++i)
{
ResultExclusiveOr ^= arr[i];
}
size_t FirstBitIs1Num = FindFirstBitIs1(ResultExclusiveOr);
*Num1 = 0; *Num2 = 0;
for (int i = 0; i < lenth; ++i)
{
if (arr[i] & FirstBitIs1Num)
*Num1 ^= arr[i];
else
*Num2 ^= arr[i];
}
}