问题是
Given two integers x and y, calculate the Hamming distance.
Note: 0 ≤ x, y < 231.
我试图使用^运算符,只计算结果str中的1个数,但是它并没有通过所有的测试用例。例如。93^73返回11188
当它应该返回其他内容时。在
这是我的代码:
#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)
这里的代码不正确:不应该将二进制字符串转换为整数(当然不能使用以10为底的整数)。例如,由于
bin(16)[2:]
等于字符串'1000'
,您可以看到int(bin(16)[2:])
等于实际的整数1000,这不是您想要的!在在Python中,整数的
^
运算符已经为您查看它们的二进制表示。例如,在Python中,20 ^ 25
直接计算为13
,这是正确的答案,因为10100
11001
01101
现在,您可以使用Python的
count
函数来计算字符串中1
个字符的数量,从而完成您的方法。例如,'01101'.count('1')
的计算结果为3
。在相关问题 更多 >
编程相关推荐