-
Notifications
You must be signed in to change notification settings - Fork 0
/
Miscellaneous-Maximum Xor.py
65 lines (47 loc) · 1.35 KB
/
Miscellaneous-Maximum Xor.py
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
#Problem Link : https://www.hackerrank.com/challenges/maximum-xor/problem?isFullScreen=true&h_l=interview&playlist_slugs%5B%5D=interview-preparation-kit&playlist_slugs%5B%5D=miscellaneous
#Ans:
#!/bin/python3
import math
import os
import random
import re
import sys
# Complete the maxXor function below.
def binary(x):
return f'{x:032b}'
class Node:
def __init__(self):
self.child = [None, None]
class Trie:
def __init__(self):
self.root = Node()
def add(self, x):
current = self.root
for bit in map(int, binary(x)):
if current.child[bit] is None:
current.child[bit] = Node()
current = current.child[bit]
def max_xor(self, x):
result = ''
current = self.root
for bit in map(int, binary(x)):
inverted = bit ^ 1
if current.child[inverted] is not None:
result += '1'
current = current.child[inverted]
else:
result += '0'
current = current.child[bit]
return int(result, 2)
def main():
_ = int(input())
xs = list(map(int, input().split()))
trie = Trie()
for x in xs:
trie.add(x)
m = int(input())
for _ in range(m):
x = int(input())
print(trie.max_xor(x))
if __name__ == '__main__':
main()