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