Leetcode 477. Total Hamming Distance 总海明距离 解题报告

1 解题思想

题目的意思就是给了一个数组,现在求总的海明距离,其中:
1、海明距离:任意两个数在二级制的表示下(int = 32bit),每个bit对应的值是1或0,那么这两个数在这32个位置下,取值不一样的地方的总和就是海明距离
2、总的距离:该数组中,所有两两组合得到的元素的海明距离的和

看到这里,其实就可以猜到,应该不能暴力解决了

而方法也找到了一个很简单的:
int长度是32bit,一共n个数
在每个位置上,如果有k个数为1,那么就有n-k个为0
那么贡献的海明距离就贡献了 k*(n-k)

2 原题

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 (just
showing 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.
Note:
Elements of the given array are in the range of 0 to 10^9
Length of the array will not exceed 10^4.

3 AC解

public class Solution {
    /**
     *int长度是32bit,一共n个数
     * 在每个位置上,如果有k个数为1,那么就有n-k个为0
     * 那么贡献的海明距离就贡献了 k*(n-k)
     * */
    public int totalHammingDistance(int[] nums) {
        int total = 0;
        int n = nums.length;
        for (int i=0;i<32;i++){
            int counter = 0;
            for ( int j=0;j<n;j++){
                counter += (nums[j] >> i) & 0x01;
            }
            total += counter*(n - counter);
        }
        return total;

    }
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值