The problem is
Given two integers x and y, calculate the Hamming distance.
Note: 0 ≤ x, y < 231.
I tried to use the ^ operator and just count the number of 1s in the resulting str. However it did not pass all the testing cases. For instance. 93^73 returns 11188 when it's supposed to return something else.
Here is my code:
#hamming distance
class Solution(object):
def hammingDistance(x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
bin_x=int(bin(x)[2:])
bin_y=int(bin(y)[2:])
print(bin_x)
print(bin_y)
print(str(bin_x^bin_y))
#.count('1'))
hammingDistance(93,73)
Your code here is incorrect: you should not convert the binary string into an integer (certainly not using base 10). For example, since bin(16)[2:] equals the string '1000', you can see that int(bin(16)[2:]) equals the actual integer 1000, which is not what you want!
In Python, the ^ operator for integers already does the looking at their binary representations for you. For example, in Python, 20 ^ 25 directly evaluates to 13, the correct answer, because
101001100101101Now you can finish your approach by using Python's count function to count the number of 1 characters in the string. For example, '01101'.count('1') evaluates to 3.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With