发布时间:2024-06-12 17:01
import java.util.Random;
public class 寻找多余的数 {
public static void main(String[] args) {
int N=1001;
int[] arr=new int[N];
for (int i = 0; i < N-1; i++) {
arr[i]=i+1;
}
Random randInt=new Random();
arr[N-1]=randInt.nextInt(N-1)+1;//括号里面表示范围从[0-1000),后面+1表范围右移一位[1-1001)
int index=randInt.nextInt(N);
swap(arr,index,N-1);//随机下标交换
int num=searchRedundantNumber(arr);
System.out.println(arr[index]);
System.out.println(num);
}
public static int searchRedundantNumber(int[] arr){
int num=0;
for (int i = 0; i < arr.length; i++) {
num=arr[i]^num;
}
for (int i = 1; i < arr.length; i++) {
num=num^i;
}
return num;
}
public static void swap(int[] arr, int i ,int j){
arr[i]=arr[i]^arr[j];
arr[j]=arr[i]^arr[j];
arr[i]=arr[i]^arr[j];
}
}