LintCode 1217: Total Hamming Distance

  1. 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
Example 1:

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.
Example 2:

Input: [2, 1, 0]
Output: 4
Explanation: In binary representation, the 2 is 10, 1 is 01, and 0 is 00 (just
showing the four bits relevant in this case). So the answer will be:
HammingDistance(2, 1) + HammingDistance(1, 0) + HammingDistance(2, 0) = 2 + 1 + 1 = 4.
Notice
Elements of the given array are in the range of 0 to 10^9
Length of the array will not exceed 10^4.

解法1:
这题最直接的做法就是按每个位把n个数分为2组,一组是该位为1的,另一组是该位为0的。
对于该位而言,其产生的hamming distance是total1Count * total0Count,因为1组每个成员跟0组每个成员都有1个链接。

class Solution {
public:
    /**
     * @param nums: the gievn integers
     * @return: the total Hamming distance between all pairs of the given numbers
     */
    int totalHammingDistance(vector<int> &nums) {
        int n = nums.size();
        int totalDist = 0;
        int intSizeInBits = sizeof(int) * 8;
        for (int i = 0; i < intSizeInBits; ++i) {
            int total1Count = 0, total0Count = 0;    
            for (int j = 0; j < n; ++j) {
                total1Count += (nums[j] & (0x1 << i)) ? 1 : 0;
                //total1Count += (nums[j] >> i) & 0x1;
            }
            total0Count = n - total1Count;
            totalDist += total1Count * total0Count;
        }
        
        return totalDist;
    }
};

代码同步在
https://github.com/luqian2017/Algorithm

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值