You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

48 lines
1.1 KiB

This file contains ambiguous Unicode characters!

This file contains ambiguous Unicode characters that may be confused with others in your current locale. If your use case is intentional and legitimate, you can safely ignore this warning. Use the Escape button to highlight these characters.

package 03.mca_01;
public class Code02_EvenTimesOddTimes {
// arr中只有一种数出现奇数次
public static void printOddTimesNum1(int[] arr) {
int eor = 0;
for (int num : arr) {
eor ^= num;
}
System.out.println(eor);
}
// 请保证arr中有两种数出现奇数次其他的数都是偶数次
// 打印
public static void printOddTimesNumber(int[] arr) {
int eor = 0;
for (int num : arr) {
eor ^= num;
}
// eor = a ^ b
// 请把eor状态中最右侧的1提取出来
// eor = 0000110010
// rightOne = 0000000010 & | ^ << >> >>>
// >> 带符号右移
// >>> 不带符号右移
// java 干啥的,自己查
int rightOne = eor & (-eor);
int zuo = 0;
for (int num : arr) {
// zuo只去异或一类另一类忽略
if ((num & rightOne) == 0) {
zuo ^= num;
}
}
System.out.println("一个是 " + zuo);
System.out.println("另一个是 " + (eor ^ zuo));
}
public static void main(String[] args) {
// 5 7 521 14 10
int[] arr = { 5, 7, 14, 14, 521, 7, 10, 7, 5, 5, 521, 7, 7, 7, 5, 14 };
// 请找到 14 和 10
printOddTimesNumber(arr);
}
}