Using XOR operator for finding duplicate elements in a array fails in many cases

前端 未结 6 1995
野的像风
野的像风 2021-02-01 10:36

I came across a post How to find a duplicate element in an array of shuffled consecutive integers? but later realized that this fails for many input.

For ex:
a

6条回答
  •  春和景丽
    2021-02-01 11:05

    A XOR statement has the property that 'a' XOR 'a' will always be 0, that is they cancel out, thus, if you know that your list has only one duplicate and that the range is say x to y, 601 to 607 in your case, it is feasible to keep the xor of all elements from x to y in a variable, and then xor this variable with all the elements you have in your array. Since there will be only one element which will be duplicated it will not be cancelled out due to xor operation and that will be your answer.

    void main()
    {
        int a[8]={601,602,603,604,605,605,606,607};
        int k,i,j=601;
    
        for(i=602;i<=607;i++)
        {
            j=j^i;
        }
    
        for(k=0;k<8;k++)
        {
            j=j^a[k];
        }
    
        printf("%d",j);
    }
    

    This code will give the output 605, as desired!

提交回复
热议问题