-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathxor_between_two_arrays.cpp
More file actions
70 lines (55 loc) · 1.28 KB
/
xor_between_two_arrays.cpp
File metadata and controls
70 lines (55 loc) · 1.28 KB
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
#include <bits/stdc++.h>
using namespace std;
class TrieNode{
public:
TrieNode* l;
TrieNode *r;
bool end;
TrieNode(){
l = NULL;
r = NULL;
end = false;
}
};
void insert(TrieNode *t, int num){
TrieNode *root = t;
for(int i = 0; i <= 31; ++i){
if(((1<<i)&num) > 0){
if(root->r != NULL) root = root->r;
else{
root->r = new TrieNode();
root = root->r;
}
}
else{
if(root->l != NULL) root = root->l;
else{
root->l = new TrieNode();
root = root->l;
}
}
}
}
int xor_val(TrieNode *t, int num){
TrieNode *root = t;
int val = 0;
for(int i = 0; i <= 31; ++i){
int x = num;
if((x&(1<<i)) > 0){
if(root->l != NULL) val += (1<<i), root = root->l;
else root = root->r;
}
else{
if(root->r != NULL) val += (1<<i), root = root->r;
else root = root->l;
}
}
return val;
}
int Solution::solve(vector<int> &a, vector<int> &b) {
TrieNode *root = new TrieNode();
int res = 0;
for(auto x : a) insert(root, x);
for(auto x : b) res = max(res, xor_val(root, x));
return res;
}