-
Notifications
You must be signed in to change notification settings - Fork 229
/
Copy path1835-find-xor-sum-of-all-pairs-bitwise-and.js
71 lines (60 loc) · 1.34 KB
/
1835-find-xor-sum-of-all-pairs-bitwise-and.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
/**
* @param {number[]} arr1
* @param {number[]} arr2
* @return {number}
*/
const getXORSum = function(arr1, arr2) {
let a = 0, b = 0
for(const e of arr1) a ^= e
for(const e of arr2) b ^= e
return a & b
};
// another
// On every bit XOR acts as modulo 2 addition and AND acts as modulo 2 multiplication.
// The set {0,1} with modulo 2 addition and multiplication is the field GF(2) and the distributive property holds in every field.
/**
* @param {number[]} arr1
* @param {number[]} arr2
* @return {number}
*/
const getXORSum = function(arr1, arr2) {
const bits = Array(32).fill(0)
for (let v of arr2) {
let pos = 0;
while (v > 0) {
if (v & 1) {
bits[pos]++;
}
v = v >> 1;
pos++;
}
}
let res = 0;
for (let v of arr1) {
let pos = 0;
let tmp = 0;
while (v > 0) {
if (v & 1) {
if (bits[pos] % 2 == 1) {
tmp |= (1 << pos);
}
}
v = v >> 1;
pos++;
}
res ^= tmp;
}
return res;
};
// another
/**
* @param {number[]} arr1
* @param {number[]} arr2
* @return {number}
*/
const getXORSum = function(arr1, arr2) {
let x1 = arr1[0], x2 = arr2[0]
for(let i = 1; i < arr1.length; i++) x1 ^= arr1[i]
for(let i = 1; i < arr2.length; i++) x2 ^= arr2[i]
return x1 & x2
};