我已经回答了以下kata:Lost number in number sequence。描述为:

“给出了一个从1到N的有序数字序列。一个数字可能已从中删除,然后其余数字混合在一起。找到被删除的数字。

例:

The starting array sequence is [1,2,3,4,5,6,7,8,9]
The mixed array with one deleted number is [3,2,4,6,7,8,1,9]
Your function should return the int 5.


如果没有从数组中删除任何数字,并且没有任何区别,则函数应返回int 0。

请注意,N可以为1或更小(在后一种情况下,第一个数组为[])。”

我写了一个简单的答案:

import java.util.*;

  public class Kata {
    public static int findDeletedNumber (int[] arr, int[] mixedArr) {
      Arrays.sort(mixedArr);
      for(int i = 0; i < arr.length; i++){
        try{
          if(arr[i] != mixedArr[i]){
            return arr[i];
          }
        }catch(ArrayIndexOutOfBoundsException e) {
          return arr[i];
        }
      }
      return 0;
    }
}


我在阅读别人的答案,发现其中的一个很难理解。

import java.util.Arrays;

public class Kata {
    public static int findDeletedNumber(int[] arr, int[] mixedArr) {
        return Arrays.stream(arr).reduce((a, b) -> a ^ b).orElse(0) ^ Arrays.stream(mixedArr).reduce((a, b) -> a ^ b).orElse(0);
    }
}


答案的链接:https://www.codewars.com/kata/reviews/595be553429e11365c00006f/groups/59bef3a1eda42eb0bc001612

如果有人在乎并且耐心写一个解释和/或跟踪,我想寻求帮助。目前,我可以看到答案,但我不理解。 🤯

另外,我尝试自己阅读以下内容:
What does the ^ operator do in Java?
https://www.geeksforgeeks.org/bitwise-operators-in-java/

最佳答案

异或表的真值表(异或)

X   Y    result
0   0    0
0   1    1
1   0    1
1   1    0


X^Y是什么意思?让我们看一个例子,5^6

dec       bin

5     =  101
6     =  110
------------------ xor
3     =  011


对两个数字进行异或运算只是将两个数字转换为二进制,然后将规则应用于真值表。

查看上表,很明显X^X = 0 for any integer X

5     =  101
5     =  101
------------------ xor
0     =  000


X^0 = X

5     =  101
0     =  000
------------------ xor
5     =  101


给定两个数组,对两个数组中的每个元素进行异或,然后对结果进行异或

(1 ^ 2 ^ 3 ^ 4 ^ 5 ^ 6 ^ 7 ^ 8 ^ 9) ^ (3 ^ 2 ^ 4 ^ 6 ^ 7 ^ 8 ^ 1 ^ 9)


并且由于X^Y = Y^XX^Y^Z = (X^Y)^Z = X^(Y^Z)您可以将以上内容重新排列为

(1 ^ 1) ^ ( 2 ^ 2) ^ (3 ^ 3) ^ (4 ^ 4)  ^ (5) ^ (6 ^ 6) ^ (7 ^ 7) ^ (8 ^ 8) ^ (9 ^ 9)


除缺少的数字(即5)外,其他所有内容相互抵消。

10-07 19:53
查看更多