题目描述
一种数出现奇数次,其他所有数出现偶数次 int[] arr 输出这个数
案例如下
输入 1 2 3 4 4 3 2
输出 1
思路用异或进行操作,因为异或两个相同的数异或的话为0,0异或N为N
所以直接用0依次异或所有
AC代码如下
package zuochengyun;
import java.util.Scanner;
public class code03 {
/*
* 题目描述
* 一种数出现奇数次,其他所有数出现偶数次 int[] arr 输出这个数
* */
public static void main(String[] args) {
// int[] arr1 = { 3, 3, 2, 3, 1, 1, 1, 3, 1, 1, 1 };
System.out.println("请输入:");
Scanner sc = new Scanner(System.in);
String str=sc.nextLine().toString();
String[] arr=str.split(" ");
int[] b=new int[arr.length];
//
for (int j=0;j<b.length;j++){
b[j]=Integer.parseInt(arr[j]);
System.out.println(b[j]);
}
printOdd(b);
}
public static void printOdd(int [] arr) {
int eor=0;
for (int cur : arr){
//异或操作
eor ^=cur;
}
System.out.println(eor);
}
}