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

前端 未结 6 1988
野的像风
野的像风 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:27

    Here is the code shown in the original question, which is different than your implementation. You have modified it to use a local variable instead of the last member of the array, that makes a difference:

    for (int i = 1; i < 1001; i++)
    {
       array[i] = array[i] ^ array[i-1] ^ i;
    }
    
    printf("Answer : %d\n", array[1000]);
    

提交回复
热议问题