[leetcode, python] Total Hamming Distance 多个数字之间的汉明距离

来源:互联网 发布:合肥知茵女装 编辑:程序博客网 时间:2024/05/16 05:40

问题描述:

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.Now your job is to find the total Hamming distance between all pairs of the given numbers.Example:Input: 4, 14, 2Output: 6Explanation: In binary representation, the 4 is 0100, 14 is 1110, and 2 is 0010 (justshowing the four bits relevant in this case). So the answer will be:HammingDistance(4, 14) + HammingDistance(4, 2) + HammingDistance(14, 2) = 2 + 2 + 2 = 6.

解决方案:

class Solution(object):    def totalHammingDistance(self, nums):        """        :type nums: List[int]        :rtype: int        """        if len(nums)==0:            return 0        else:            # 将所有数字转换成的二进制字符串            nums_bin_str = [bin(item)[2:] for item in nums]            # 以最长的二进制字符串为标准,将所有二进制字符串长度统一            len_num = [len(item) for item in nums_bin_str]            max_len = max(len_num)            append_len = [max_len-item for item in len_num]            nums_bin_list = ['0'*item+nums_bin_str[i] for i,item in enumerate(append_len)]            # 开始计算汉明距离            total_dist = 0            for i in range(max_len):                # 每一列‘1’的个数乘以每一列‘0’的个数即为该列的汉明距离                col_list = [x[i] for x in nums_bin_list]                one_dist = col_list.count('1') * col_list.count('0')                # 将所有列的汉明距离相加即为总的汉明距离                total_dist += one_dist            return total_dist

思路说明:

先统一二进制字符串的长度,形成一个矩阵;再计算矩阵每一列‘1’的个数乘以‘0’的个数的值,该值为该列的汉明距离;最后将每列的结果相加即为总的汉明距离。
0 0