Count number of bits to convert one integer to another integer Return the number of bits (N) that will need to be changed in order to convert an integer(X), into another integer(Y).


  Constraint: 0 &lt;= X &lt;= Y &lt;= 2**128
  
  Example:
  
  X = 1, Y = 2 => N = 2
  
  X = 2, Y = 3 => N = 1
  
  X = 0, Y = 4 => N = 1


I have written following code, how to improve it?

def bit_diff(n1,n2):
    cmn_d = n1 &amp; n2
    all_d = n1 | n2
    diff = all_d - cmn_d
    cnt = 0
    while diff:
        if diff &amp; 1:
            cnt+=1
        diff&gt;&gt;=1
    return cnt

print bit_diff(1,2)
cmn_d = n1 &amp; n2
all_d = n1 | n2
diff = all_d - cmn_d



There is an operator for that:

diff = n1 ^ n2




Having found the bits that differ, you want to count the set bits of diff, also known as the population count or the Hamming weight. The approach you use is simple and valid, but there are higher performing approaches which parallelise it (see here and following sections).

However, the standard approaches for the fastest parallel implementations without direct hardware support are based on fixed-width integers, and they typically go to 32 bits or 64 bits; since your specification says that you want to support 128-bit integers, you'll have to extrapolate, although it's not that hard.