LeetCode——Hamming Distance

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

public class Solution {
public int hammingDistance(int x, int y) {
    int cnt = 0;
    int ans = x ^ y;
    while(ans > 0){
        if(ans%2==1)
        {
            cnt+=1;
        }
        ans/=2;
    }
    return cnt;
}

}

477 Total Hamming Distance

Total Accepted: 14132
Total Submissions: 30521
Difficulty: Medium
Contributors:
kevin.xinzhao@gmail.com
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.

public class Solution {
public int totalHammingDistance(int[] nums) {
    int n = 31;
    int len = nums.length;
    int[] countOfOnes = new int[n];

    for (int i = 0; i < len; i++)//对待每一个数字
    {
        for (int j = 0; j < n; j++)//每一位数字
        {
            countOfOnes[j] += (nums[i] >> j) & 1;//统计这一个位置是0还是1
        }
    }
    int sum = 0;
    for (int count: countOfOnes) {
        sum += count * (len - count);
    }
    return sum;
}

}

解释一下他大概的原理:

如果从每两个数字去组合考虑那么会LTE,所以从所有数字的某一个位置考虑,假设这个数组上所有数字的某一个位置上已知有x个1,y个0,那么这个位置上最终各种各样全部异或一遍加起来应该就是 x*y个1(因为x^x = y^y =0),即,你在这个位置所有数字有x个1,y个0,异或之后留下来就会有x*y个1;

感想

脑子是个好东西

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值