Style-wise, you could work on your variable naming (realizing that naming is one of the two hardest things in programming).
cmn_d
could be common_digits
, all_d
all_digits
and cnt
count
. This would make it slightly easier to read
Python also has an official style-guide, PEP8, which recommends using spaces around operators, so you would write diff >>= 1
and count += 1
.
Performance wise, your code is already quite fast (not that surprising, considering that it does just bit-shifts), so I don't think a different approach is needed here, although the improvement in @PeterTaylors answer is slightly faster:
+----+----+--------+--------------+
| n1 | n2 | Harsha | Peter Taylor |
+----+----+--------+--------------+
| 1 | 2 | 322 ns | 276 ns |
| 2 | 3 | 255 ns | 202 ns |
| 0 | 4 | 389 ns | 326 ns |
+----+----+--------+--------------+
So, unless you need to run this more than a few million times per second on small cases, your implementation should be fine (with the small modification of using n1 ^ n2
).