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

问题描述:

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, 2

Output: 6

Explanation: 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
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值