-
Notifications
You must be signed in to change notification settings - Fork 0
/
non repeating number.py
62 lines (43 loc) · 1.45 KB
/
non repeating number.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
# Python3 program for above approach
# This function sets the values of
# *x and *y to non-repeating elements
# in an array arr[] of size n
def UniqueNumbers2(arr, n):
sums = 0
for i in range(0, n):
# Xor all the elements of the array
# all the elements occuring twice will
# cancel out each other remaining
# two unnique numbers will be xored
sums = (sums ^ arr[i])
# Bitwise & the sum with it's 2's Complement
# Bitwise & will give us the sum containing
# only the rightmost set bit
sums = (sums & -sums)
# sum1 and sum2 will contains 2 unique
# elements elements initialized with 0 box
# number xored with 0 is number itself
sum1 = 0
sum2 = 0
# Traversing the array again
for i in range(0, len(arr)):
# Bitwise & the arr[i] with the sum
# Two possibilities either result == 0
# or result > 0
if (arr[i] & sums) > 0:
# If result > 0 then arr[i] xored
# with the sum1
sum1 = (sum1 ^ arr[i])
else:
# If result == 0 then arr[i]
# xored with sum2
sum2 = (sum2 ^ arr[i])
# Print the the two unique numbers
print("The non-repeating elements are ",
sum1, " and ", sum2)
# Driver Code
if __name__ == "__main__":
arr = [2, 3, 7, 9, 11, 2, 3, 11]
n = len(arr)
UniqueNumbers2(arr, n)
# This code is contributed by akhilsaini