【发布时间】:2017-09-26 06:21:22
【问题描述】:
这个问题可能有点误导,但我不知道如何用另一种方式问它。 在hackerrank中存在如下问题:
考虑一个整数数组,其中除一个整数之外的所有整数 成对出现。换句话说,每个元素恰好出现两次 除了一个独特的元素。
给定数组查找并打印唯一元素。 [2,3,1,3,2] -> 结果是 1
我这样解决了这个问题:
private static int lonelyInteger(int[] a) {
if(a==null)
return 0;
if(a.length<2)
return a.length;
Set<Integer> set = new HashSet<>();
for(int i : a){
if(set.contains(i)){
set.remove(i);
}else{
set.add(i);
}
}
return (Integer) set.toArray()[0];
}
然而,我们发现这个问题有一个巧妙的解决方案:
private static int lonelyInteger(int[] a) {
int b = a[0];
for(int i = 1; i < a.length; i++){
b ^= a[i];
}
return b;
}
问题是我不知道它为什么起作用?! 我了解它是如何工作的,但不明白它为什么起作用? 为了理解我做了一个小程序来输出每一步的结果:
public class BitwiseOperator {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
int n = in.nextInt();
int[] a = new int[n];
int sum = 0;
in.nextLine();
String line = in.nextLine();
String[] numbers = line.split(" ");
for (int i = 0; i < numbers.length; i++) {
a[i] = Integer.valueOf(numbers[i]);
}
for (int i = 0; i < a.length; i++) {
binary(sum, a[i]);
sum ^= a[i];
binary(sum);
System.out.println();
System.out.println();
System.out.println();
}
System.out.println(sum);
}
private static void binary(int sum) {
System.out.println(String.format("%16s", Integer.toBinaryString(sum)).replace(' ', '0') + " ->" + sum);
}
private static void binary(int sum, int i) {
System.out.println(String.format("%16s", Integer.toBinaryString(sum)).replace(' ', '0') + " ->" + sum);
System.out.println("XOR");
System.out.println(String.format("%16s", Integer.toBinaryString(i)).replace(' ', '0') + " ->" + i);
System.out.println("--------");
}
}
如果输入以下输入:
5
2 3 2 1 3
输出是:
0000000000000000 ->0
XOR
0000000000000010 ->2
--------
0000000000000010 ->2
0000000000000010 ->2
XOR
0000000000000011 ->3
--------
0000000000000001 ->1
0000000000000001 ->1
XOR
0000000000000010 ->2
--------
0000000000000011 ->3
0000000000000011 ->3
XOR
0000000000000001 ->1
--------
0000000000000010 ->2
0000000000000010 ->2
XOR
0000000000000011 ->3
--------
0000000000000001 ->1
1
所以该程序确实有效但我真的需要了解为什么?
【问题讨论】:
-
A xor A == 0这就是为什么重复取消;如果我们只有一个项目是重复的,那么异或这些项目将返回不同的项目 -
@DmitryBychenko 您的评论应该是一个答案,因为它简洁、简短、全面且正确。
-
@DmitryBychenko 是的,我明白,但是当它是 A XOR B XOR C XOR A XOR B 为什么它也是 0 时会发生什么?
-
@Adelin 因为 XOR 事物的顺序无关紧要,因为 XOR 只是没有携带的加法。还有
(0 XOR A) = A,所以A XOR B XOR C XOR A XOR B=(B XOR B) XOR (C XOR X) XOR A=0 XOR 0 XOR A=0 XOR A=A。所有出现两次的都取消为零。
标签: java algorithm binary bitwise-operators