Leetcode Problem:
Summary
- Given two arrays, nums1 and nums2, return the bitwise XOR of all pairings of integers between nums1 and nums2.
Approach
- The solution uses two nested loops to iterate over the elements of nums1 and nums2
- For each element in nums1, it XORs the element with all elements in nums2
- Similarly, for each element in nums2, it XORs the element with all elements in nums1
- The XOR operation is used to combine the pairings, and the result is returned.
Complexity
- O(n*m) where n is the size of nums1 and m is the size of nums2
Explanation
- The solution iterates over the elements of nums1 and nums2 using two nested loops
- For each element in nums1, it XORs the element with all elements in nums2 using a single loop
- Similarly, for each element in nums2, it XORs the element with all elements in nums1 using another single loop
- The XOR operation is associative and commutative, so the order of the loops does not matter
- The result of the XOR operation is the bitwise XOR of all pairings of integers between nums1 and nums2.
Solution Code:
class Solution {
public:
int xorAllNums(vector& nums1, vector& nums2) {
int n1 = (nums1.size()-1) % 2;
int n2 = (nums2.size()-1) % 2;
int ans = 0;
for(int i = 0 ; i < nums1.size(); i++){
for(int j = 0 ; j <= n2; j++){
ans ^= nums1[i];
}
}
for(int i = 0 ; i < nums2.size(); i++){
for(int j = 0; j <= n1; j++){
ans ^= nums2[i];
}
}
return ans;
}
};
'알고리즘' 카테고리의 다른 글
Neighboring Bitwise XOR (0) | 2025.03.05 |
---|---|
Check if Number is a Sum of Powers of Three (0) | 2025.03.04 |
Minimize XOR (0) | 2025.03.04 |
Find the Prefix Common Array of Two Arrays (0) | 2025.03.04 |
Construct K Palindrome Strings (0) | 2025.03.04 |