4
\$\begingroup\$

I was solving this Leetcode challenge about Hamming Distance. Would love feedback on my syntax and code style. Here's the challenge description:

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, calculate the Hamming distance.

Note: 0 ≤ x, y < 231.

Example:

Input: x = 1, y = 4

Output: 2

Explanation:

1 (0 0 0 1)
4 (0 1 0 0)
 ↑ ↑

The above arrows point to positions where the corresponding bits are
different.

Here's my solution:

 def hammingDistance(x: 'int', y: 'int') -> 'int':
 bin_x = bin(x)[2:]
 bin_y = bin(y)[2:]
 len_x = len(bin_x)
 len_y = len(bin_y)
 if len_x != len_y:
 if len_x > len_y:
 zeros = '0' * (len_x - len_y)
 bin_y = zeros + bin_y
 else:
 zeros = '0' * (len_y - len_x)
 bin_x = zeros + bin_x
 dist = 0
 for x,y in zip(bin_x, bin_y):
 if x!=y:
 dist += 1
 return dist 
200_success
146k22 gold badges190 silver badges478 bronze badges
asked Feb 16, 2019 at 19:15
\$\endgroup\$

1 Answer 1

6
\$\begingroup\$

That's a reasonable approach, but converting to strings early and then doing everything on strings leads to a lot of extra code. Note that this construct in your code, if x!=y, essentially XORs two bits and then does something if the result of that XOR is 1.

Doing that XOR directly on the integers makes the problem simpler, the whole problem of having to pad with zeroes disappears (which about halves the code size already), and the problem is reduced to "count the ones in binary". That could still be done with a similar loop, but there is a short-cut:

return bin(x ^ y).count('1')
answered Feb 17, 2019 at 4:39
\$\endgroup\$

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.