LeetCode每日一题(1835. Find XOR Sum of All Pairs Bitwise AND)

本文介绍了一种利用位运算解决特定数学问题的方法。通过观察数组元素间的位运算特性,将复杂的问题转化为简单的位操作,实现了快速计算任意两个数组中所有元素按位与后XOR值的总和。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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.

Example 1:

Input: arr1 = [1,2,3], arr2 = [6,5]
Output: 0

Explanation: The list = [1 AND 6, 1 AND 5, 2 AND 6, 2 AND 5, 3 AND 6, 3 AND 5] = [0,1,2,0,2,1].
The XOR sum = 0 XOR 1 XOR 2 XOR 0 XOR 2 XOR 1 = 0.

Example 2:

Input: arr1 = [12], arr2 = [4]
Output: 4

Explanation: The list = [12 AND 4] = [4]. The XOR sum = 4.

Constraints:

  • 1 <= arr1.length, arr2.length <= 105
  • 0 <= arr1[i], arr2[j] <= 109

纯数学问题
(a1 ^ a2) & (b1 ^ b2) = (a1 & b1) ^ (a1 & b2) ^ (a2 & b1) ^ (a2 & b2)
上面的等式右边是题目描述的情况, 左边是转化后的形式, 这样我们要的答案就是:
(arr1[0] ^ arr1[1] … ^ arr1[arr1.len()-1]) & (arr2[0] ^ arr2[1] … ^ arr2[arr2.len()-1])



impl Solution {
    pub fn get_xor_sum(arr1: Vec<i32>, arr2: Vec<i32>) -> i32 {
        let x1 = arr1.into_iter().fold(0, |s, v| s ^ v);
        let x2 = arr2.into_iter().fold(0, |s, v| s ^ v);
        x1 & x2
    }
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值