Bit operation to find the repeated number in the array

Find the number that is repeated in the array

First, you need to create an array.
int n=1001; int[] a=new int[n]; for(int i=0;i<a.length-1;i++) { a[i]=i+1; }
Then you need to insert a random number into the last number in this array, and you also need to get a random subscript, so that the random number is inserted into a random position in the array; in order to find the repetition of a number
a[a.length-1]=new Random().nextInt(n)+1;//求随机数放在数组最后 int index=new Random().nextInt(n);//求随机下标插入随机数 int b=a[a.length-1];//对随即下标数值进行互换 a[a.length-1]=a[index]; a[index]=b;
* *Next briefly explain the principle of the code. First, we must understand the definition of XOR. The difference is 1, and the same is zero. As in the above code, we take a number within 1000, and randomly obtain a random number in it, and divide one of them. All other random numbers are single.
We can add another equal number within 1000 at will, and make the two sets of numbers XOR. Then the original single number becomes double, and the repeated number becomes three. Then the XOR of two identical numbers is zero, and the XOR of zero with any number is another number. If three of the repeated numbers are XORed, they are still repeated numbers, so that the repeated number can be obtained. The number, the code is as follows
** The int x=0; for(int i=1;i<=n-1;i++) { x=x^i; } for(int i=0;i<=a.length-1;i++) { //进行异或运算 x=x^a[i]; } System.out.println(x);
last output can get the repeated value

Another method is auxiliary space

Create a new array, take the value of the above array as the subscript of the new array, and then for loop, after i select which happ[a[i]]++ operation, then use if to determine which value is 2, break out Just output.

Guess you like

Origin blog.csdn.net/weixin_45956604/article/details/105159906