So what I need is a python function to count the binary that are coincident on two numbers written in binary but with a fixed, known length. For example, if n = 8
is the binary length, then:
a = 0011 0110
b = 0101 1111
--------------
c = 1001 0110 -> 4
Should get a result of 4
. each 0
on c is a non coincidence and each 1
means coincidence. As c has 4 one's, then the result is 4.
I need it to be as fast as possible.
This was my final solution that I think is quite effective:
bin(a ^ b)[2:].zfill(n).count("0")
Explanation
The logic was to use xor to get the number of coincidences. With XOR, I actually get the inverse of the example done in the question, as a coincidence will mean a 0
and a non coincidence will mean a 1
. So I will have to negate it, but before that I should make the number of n
size because the answer is actually 110 1001
and so I'll get a response of 3 instead of 4.