【问题标题】:XOR operation returning only non-pair element in integer arrayXOR 操作仅返回整数数组中的非对元素
【发布时间】:2015-03-31 01:28:47
【问题描述】:

我在解决 Hackerrank 挑战时遇到了这个问题。

/*
Problem Statement

There are N integers in an array A. All but one integer occur in pairs. Your task is to find the number that occurs only once.

Input Format

The first line of the input contains an integer N, indicating the number of integers. The next line contains N space-separated integers that form the array A.

Constraints

1≤N<100 
N % 2=1 (N is an odd number) 
0≤A[i]≤100,∀i∈[1,N]
Output Format

Output S, the number that occurs only once.
*/

我在这种情况下编写的常规解决方案非常复杂,有很多嵌套的 if 循环。经过一番搜索,我发现这个解决方案通过简单地将整数数组中的所有元素相互异或来解决问题,结果是孤独的整数。

这是相关的方法(main() 方法,它接受输入并将其解析为整数数组,未显示,因为它在这里不相关):

    static int lonelyinteger(int[] a) {

        int n = a.length;
        int result = 0;
        for( int i = 0; i < n; i++) {
            result = result ^ a[i];
        }

        return  result;

}

我不确定这个 XOR 操作如何能够返回数组中的“孤独整数”。我知道 XOR 的两个属性,如:

 1. a^a=0
 2. a^0=a

但除此之外,我不太明白 XOR 是如何在这里工作的。

在 SO 上有 another question 具有相同的内容,但这提出了一个不同的问题,所以我不得不问这个(再次)。

如果有人能提供此 XOR 操作的详细解释,我将不胜感激。

【问题讨论】:

    标签: arrays xor


    【解决方案1】:

    由于任何aa^a 等于0,所有匹配的整数对将相互抵消,留下0。然后与最终数字进行异或。由于任何a0^a 等于a,因此结果将是最终数字。 简单演示:

    $ ruby -e 'puts [1,1,2,2,3,3,4,5,5,6,6].reduce :^'
    4
    

    如果您查看各个对,您会明白为什么会这样:

    1 ^ 1 = 0 
    0 ^ 2 = 2
    2 ^ 2 = 0
    0 ^ 3 = 3
    3 ^ 3 = 0
    0 ^ 4 = 4
    4 ^ 5 = 1
    1 ^ 5 = 4
    4 ^ 6 = 2
    2 ^ 6 = 4
    

    结果在 0 和最新的数字之间切换,直到你找到孤独者;之后,它会在那个数字和......当你用最新的新数字异或它时得到的任何东西之间切换。那里的实际值无关紧要,因为当您对该数字的第二个副本进行异或运算时,它将被删除,然后您将返回到单例的副本。

    我对数字进行了排序以便于识别单例,但由于 XOR 会自行撤消,所以顺序根本不重要:

    $ ruby -e 'puts [6,3,4,1,1,2,2,6,3,5,5].reduce :^'
    4
    

    6 ^ 3 是...某个数字,然后那个数字 ^ 4 是某个其他数字,然后您将其与 1 进行异或运算,这些都不重要,因为您撤消了 1,然后您又输入了另一个使用 2 的中间结果并立即撤消它,然后撤消 6 和 3,所以你又回到了 4。你用 5 异或得到另一个短暂的数字,然后被最后的 5 冲走,离开,再一次,4。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-08
      • 1970-01-01
      • 2012-12-05
      • 2019-07-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多