[LeetCode] Find XOR Sum of All Pairs Bitwise AND

1835. Find XOR Sum of All Pairs Bitwise AND

The XOR sum of a list is the bitwise XOR of all its elements. If the list only contains one element, then its XOR sum will be equal to this element.

For example, the XOR sum of [1,2,3,4] is equal to 1 XOR 2 XOR 3 XOR 4 = 4, and the XOR sum of [3] is equal to 3.
You are given two 0-indexed arrays arr1 and arr2 that consist only of non-negative integers.

Consider the list containing the result of arr1[i] AND arr2[j] (bitwise AND) for every (i, j) pair where 0 <= i < arr1.length and 0 <= j < arr2.length.

Return the XOR sum of the aforementioned list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
class Solution {
public:
int getXORSum(vector<int>& arr1, vector<int>& arr2) {
int arr2XOR = arr2.front();
for(int i = 1; i < arr2.size(); i++) {
arr2XOR ^= arr2[i];
}
int res = arr1[0] & arr2XOR;
for(int i = 1; i < arr1.size(); i++) {
res ^= (arr1[i] & arr2XOR);
}

return res;
}
};

Author: Song Hayoung
Link: https://songhayoung.github.io/2021/04/18/PS/LeetCode/find-xor-sum-of-all-pairs-bitwise-and/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.