📌  相关文章
📜  数组中每个可能对的总和的异或

📅  最后修改于: 2021-04-23 07:30:51             🧑  作者: Mango

给定大小为n的数组A。任务是生成一个新的序列N,其大小为N ^ 2,具有数组A的每一对元素的和,并找到所形成的所有对的和的异或值。
注意:此处(A [i],A [i]),(A [i],A [j]),(A [j],A [i])都被视为不同的对。
例子:

Input: arr = {1, 5, 6}
Output: 4
B[3*3] = { 1+1, 1+5, 1+6, 5+1, 5+5, 5+6, 6+1, 6+5, 6+6}
B[9] = { 2, 6, 7, 6, 10, 11, 7, 11, 12}
So, 2 ^ 6 ^ 7 ^ 6 ^ 10 ^ 11 ^ 7 ^ 6 ^ 11 ^ 12 = 4

Input :1, 2
Output :6

天真的方法是运行两个循环。考虑每一对,取它们的和并计算所有对的和。
一种有效的方法基于相同值的xor为0的事实。
所有对(a [i],a [j])和(a [j],a [i])都将具有相同的总和。因此,它们的xor值将为0。只有像(a [i],a [i])之类的对才会给出不同的结果。因此,将给定数组的所有元素的异或乘以2。

C++
// C++ program to find XOR of
// sum of every possible pairs
// in an array
#include 
using namespace std;
 
// Function to find XOR of sum
// of all pairs
int findXor(int arr[], int n)
{
 
    // Calculate xor of all the elements
    int xoR = 0;
    for (int i = 0; i < n; i++) {
        xoR = xoR ^ arr[i];
    }
 
    // Return twice of xor value
    return xoR * 2;
}
 
// Drivers code
int main()
{
    int arr[3] = { 1, 5, 6 };
    int n = sizeof(arr) / sizeof(arr[0]);
 
    cout << findXor(arr, n);
 
    return 0;
}


Java
// Java program to find XOR of
// sum of every possible pairs
// in an array
import java.io.*;
 
class GFG {
     
    // Function to find XOR of sum
    // of all pairs
    static int findXor(int arr[], int n)
    {
     
        // Calculate xor of all the
        // elements
        int xoR = 0;
        for (int i = 0; i < n; i++) {
            xoR = xoR ^ arr[i];
        }
     
        // Return twice of xor value
        return xoR * 2;
    }
     
    // Drivers code
    public static void main (String[] args)
    {
        int arr[] = { 1, 5, 6 };
        int n = arr.length;
        System.out.println( findXor(arr, n));
    }
}
 
// This code is contributed by anuj_67.


Python3
# Python3 program to find
# XOR of sum of every
# possible pairs in an array
 
# Function to find XOR
# of sum of all pairs
def findXor(arr,n):
 
    # Calculate xor of
    # all the elements
    xoR = 0;
    for i in range (0, n ) :
        xoR = xoR ^ arr[i]
     
    # Return twice of
    # xor value
    return xoR * 2
 
# Driver code
arr = [ 1, 5, 6 ]
n = len(arr)
print(findXor(arr, n))
 
# This code is contributed
# by ihritik


C#
// C# program to find XOR of
// sum of every possible pairs
// in an array
using System;
 
class GFG {
     
    // Function to find XOR of sum
    // of all pairs
    static int findXor(int []arr, int n)
    {
     
        // Calculate xor of all the
        // elements
        int xoR = 0;
        for (int i = 0; i < n; i++) {
            xoR = xoR ^ arr[i];
        }
     
        // Return twice of xor value
        return xoR * 2;
    }
     
    // Drivers code
    public static void Main ()
    {
        int []arr = { 1, 5, 6 };
        int n = arr.Length;
        Console.WriteLine( findXor(arr, n));
    }
}
 
// This code is contributed by anuj_67.


PHP


输出:
4