异或的应用

//问题描述:数组中只出现一次的数有两个,其他都是成对出现的,请找出这两个数只出现一次的数

实现的代码:

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];
    }
}
原文地址:https://www.cnblogs.com/shihaochangeworld/p/5472314.html