2425. Bitwise XOR of All Pairings #1155
-
Topics: You are given two 0-indexed arrays, Return the bitwise XOR of all integers in Example 1:
Example 2:
Constraints:
Hint:
|
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 2 replies
-
We need to think carefully about how the bitwise XOR operates and how the pairing of elements in Key Observations:
Approach:
Using these observations, we can reduce the problem to counting the number of times each bit is set (odd number of times) across all pairings. Plan:
Let's implement this solution in PHP: 2425. Bitwise XOR of All Pairings <?php
function xorAllNums($nums1, $nums2) {
$m = count($nums1); // length of nums1
$n = count($nums2); // length of nums2
$result = 0;
// Iterate over all 32 possible bit positions (0 to 31)
for ($bit = 0; $bit < 32; $bit++) {
$count1 = 0; // Count of 1's in the $bit-th position in nums1
$count2 = 0; // Count of 1's in the $bit-th position in nums2
// Count 1's in nums1 for the $bit-th position
foreach ($nums1 as $num) {
if (($num >> $bit) & 1) {
$count1++;
}
}
// Count 1's in nums2 for the $bit-th position
foreach ($nums2 as $num) {
if (($num >> $bit) & 1) {
$count2++;
}
}
// Calculate the number of 1's in the $bit-th position in nums3
$totalCount = $count1 * $n + $count2 * $m;
// If totalCount is odd, set the $bit-th bit in result
if ($totalCount % 2 == 1) {
$result |= (1 << $bit);
}
}
return $result;
}
// Example 1
$nums1 = [2, 1, 3];
$nums2 = [10, 2, 5, 0];
echo xorAllNums($nums1, $nums2); // Output: 13
// Example 2
$nums1 = [1, 2];
$nums2 = [3, 4];
echo xorAllNums($nums1, $nums2); // Output: 0
?> Explanation:
Complexity:
Example Walkthrough:Example 1: $nums1 = [2, 1, 3];
$nums2 = [10, 2, 5, 0];
echo xorAllPairings($nums1, $nums2); // Output: 13 Example 2: $nums1 = [1, 2];
$nums2 = [3, 4];
echo xorAllPairings($nums1, $nums2); // Output: 0 This solution is efficient and works within the problem's constraints. |
Beta Was this translation helpful? Give feedback.
We need to think carefully about how the bitwise XOR operates and how the pairing of elements in
nums1
andnums2
affects the result.Key Observations:
Each element in
nums1
pairs with every element innums2
, and vice versa.In
nums3
, each number fromnums1
andnums2
appears multiple times:nums1
appearsn
times (wheren
is the length ofnums2
).nums2
appearsm
times (wherem
is the length ofnums1
).The XOR operation has a property that if a number appears an even number of times, it will cancel out (because
x ^ x = 0
), and if it appears an odd number of times, it contributes to the final XOR result.Approach: