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
1 Answer 1
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')
Explore related questions
See similar questions with these tags.