LeetCode 1835: Find XOR Sum of All Pairs Bitwise AND
Problem Description
Explanation
To solve this problem, we can use the properties of XOR and bitwise AND operations. We need to find the bitwise AND of all pairs of elements from arr1
and arr2
, and then calculate the XOR sum of those results.
The key idea is to observe that for any two numbers a
and b
, the XOR sum of their bitwise ANDs is the same as the bitwise AND of their XORs, i.e., a & b = (a ^ b) & b
.
Therefore, we can iterate through each pair of elements from arr1
and arr2
, calculate the XOR of the pair, and then bitwise AND it with the second element of the pair. Finally, we calculate the XOR sum of all these results.
Solutions
class Solution {
public int getXORSum(int[] arr1, int[] arr2) {
int xorArr1 = 0;
for (int num : arr1) {
xorArr1 ^= num;
}
int xorArr2 = 0;
for (int num : arr2) {
xorArr2 ^= num;
}
return xorArr1 & xorArr2;
}
}
Loading editor...