Leetcode #461. Hamming Distance

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 ≤ xy < 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.

题意:汉明码,数字传输时会转换成二进制,对两个二进制进行统计,看下有多少不同的数字;

想法:就是转换成二进制,想法其实很简单,唯一需要考虑的就是位数不同,只要处理的时候高位补位就好

参考代码:

 1 class Solution(object):
 2     def hammingDistance(self, x, y):
 3         """
 4         :type x: int
 5         :type y: int
 6         :rtype: int
 7         """
 8         small,big = (bin(x)[2:],bin(y)[2:]) if y>x else (bin(y)[2:],bin(x)[2:])
 9            small = '0'*(len(big)-len(small)) + small
10         sum=0
11         for (i,j) in zip(small,big):
12             if i!=j:
13                 sum+=1
14         return sum

 

Python语法总结:

bin(x):返回一个整数 int 或者长整数 long int 的二进制表示。

例子:

1 >>>bin(10)
2 '0b1010'
3 >>> bin(20)
4 '0b10100'

 

zip(a,b):函数用于将可迭代的对象作为参数,将对象中对应的元素打包成一个个元组,然后返回由这些元组组成的列表。如果各个迭代器的元素个数不一致,则返回列表长度与最短的对象相同,利用 * 号操作符,可以将元组解压为列表。可以理解为矩阵转置。

例子:

1 >>>a = [1,2,3]
2 >>> b = [4,5,6]
3 >>> c = [4,5,6,7,8]
4 >>> zipped = zip(a,b)     # 打包为元组的列表
5 [(1, 4), (2, 5), (3, 6)]
6 >>> zip(a,c)              # 元素个数与最短的列表一致
7 [(1, 4), (2, 5), (3, 6)]
8 >>> zip(*zipped)          # 与 zip 相反,可理解为解压,返回二维矩阵式
9 [(1, 2, 3), (4, 5, 6)]

 

posted @ 2017-08-17 15:38  lhppom  阅读(97)  评论(0编辑  收藏  举报