题目
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.
题意
汉明码,数字传输时会转换成二进制,对两个二进制进行统计,看下有多少不同的数字;
想法
就是转换成二进制,想法其实很简单,唯一需要考虑的就是位数不同,只要处理的时候高位补位就好
参考代码:
class Solution(object):
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
small,big = (bin(x)[2:],bin(y)[2:]) if y>x else (bin(y)[2:],bin(x)[2:])
small = '0'*(len(big)-len(small)) + small
sum=0
for (i,j) in zip(small,big):
if i!=j:
sum+=1
return sum
Python语法总结:
bin(x):返回一个整数 int 或者长整数 long int 的二进制表示。
例子:
1 >>>bin(10)
2 ‘0b1010’
3 >>> bin(20)
4 ‘0b10100’
zip(a,b):函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。可以理解为矩阵转置。
例子:
>>>a = [1,2,3]
>>> b = [4,5,6]
>>> c = [4,5,6,7,8]
>>> zipped = zip(a,b) # 打包为元组的列表
[(1, 4), (2, 5), (3, 6)]
>>> zip(a,c) # 元素个数与最短的列表一致
[(1, 4), (2, 5), (3, 6)]
>>> zip(*zipped) # 与 zip 相反,可理解为解压,返回二维矩阵式
[(1, 2, 3), (4, 5, 6)]