Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Leetcode 2425. Bitwise XOR of All Pairings #141

Open
Woodyiiiiiii opened this issue Oct 1, 2022 · 0 comments
Open

Leetcode 2425. Bitwise XOR of All Pairings #141

Woodyiiiiiii opened this issue Oct 1, 2022 · 0 comments

Comments

@Woodyiiiiiii
Copy link
Owner

这道题咋一看很复杂。运算全是异或。我一开始想计算每个位置的1和0的出现次数,再运算,但显然太复杂了。

细想一下,异或的关键在于异或自身偶数次结果为0,异或自身寄次数结果为自身

所以在这题中,写出最后公式是,假如数组1是[a, b],数组2是[c, d]: (a ^ c) ^ (a ^ d) ^ (b ^ c) ^ (b ^ d) = ?

其实其等于a ^ c ^ a ^ d ....,把括号拆除。这样就可以用异或来简化算法了。观察!

class Solution {
    public int xorAllNums(int[] nums1, int[] nums2) {
        int n1 = nums1.length;
        int n2 = nums2.length;
        
        int res = 0;
        if (n2 % 2 != 0) {
            for (int n : nums1) {
                res ^= n;
            }
        }
        if (n1 % 2 != 0) {
            for (int n : nums2) {
                res ^= n;
            }
        }
        
        return res;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant