DEV Community

kalokli8
kalokli8

Posted on

XOR Python

XOR Operator in Python is also known as “exclusive or”. It compares two binary numbers bitwise if two bits are identical XOR outputs as 0 and when two bits are different then XOR outputs as 1.

Bitwise operators in Python are also called binary operators. In calculation, the integers are first converted into binary, and later the operations are performed bit by bit.

a=  5  #0101
b = 3  #0011

result  = (a ^ b) #0110

print(result)

# Output
# 6 (0110)
Enter fullscreen mode Exit fullscreen mode
print(True ^ True) // False
print(True ^ False) // True
print(False ^ True) // True
print(False ^ False) //False
Enter fullscreen mode Exit fullscreen mode

find non-duplicate in [7,3,3,4,4,5,5]

def singleNumber(self, nums: List[int]) -> int:
    n=len(nums)
    r=nums[0]
    for i in range(1,n):
        r = r ^ nums[i] 

    return r

r = 7 ^ 3 ^ 5 ^ 4 ^ 5 ^ 3 ^ 4

Since XOR is associative and commutative, above
expression can be written as:
r = 7 ^ (3 ^ 3) ^ (4 ^ 4) ^ (5 ^ 5)
= 7 ^ 0 ^ 0 ^ 0
= 7 ^ 0
= 7
Enter fullscreen mode Exit fullscreen mode

credit: https://itsmycode.com/xor-in-python/

Top comments (0)