Reputation: 169
I have two binary numbers
01110
and
10010
It is easy to see that the first position they differ is the third from the right. How do I find this in python? Let's say, I would hve something like sdb(a, b)
and that would return 3 in this case. Are there better options than looping over the 2 number's bit from the right using leftshift?
Upvotes: 1
Views: 231
Reputation: 11992
you can XOR
the two numbers and XOR will return 0 when both bits are the same and 1 when both bits are different. so the result of 01110 ^ 10010
will be 11100
we can then parse this as a string using rindex to look for the first 1
we encounter from the right hand side as this will be the first place the bits were different. This will give us the index from the left. we then subtract this from the length of the xor string to get the bit count from the right where the difference occurs.
def sdb(a: int, b: int) -> int:
try:
xor_string = f'{a^b:b}'
index = len(xor_string) - xor_string.rindex('1')
except ValueError as ve:
#if no bits are different return index 0
index = 0
return index
num1 = int('01110',2)
num2 = int('10010',2)
print(sdb(num1, num2))
Upvotes: 3