snippetpythonModerate
Count number of bits to convert one integer to another integer
Viewed 0 times
numberconvertbitsoneanothercountinteger
Problem
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 N = 2
X = 2, Y = 3 => N = 1
X = 0, Y = 4 => N = 1
I have written following code, how to improve it?
Constraint: 0 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 & n2
all_d = n1 | n2
diff = all_d - cmn_d
cnt = 0
while diff:
if diff & 1:
cnt+=1
diff>>=1
return cnt
print bit_diff(1,2)Solution
cmn_d = n1 & n2
all_d = n1 | n2
diff = all_d - cmn_dThere is an operator for that:
diff = n1 ^ n2Having 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.
Code Snippets
cmn_d = n1 & n2
all_d = n1 | n2
diff = all_d - cmn_ddiff = n1 ^ n2Context
StackExchange Code Review Q#161100, answer score: 10
Revisions (0)
No revisions yet.