[LC]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.

Note:
0 ≤ xy < 231.

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.

二、我的思路

首先想到用位运算。

先把x和y异或(^),记作xor,里面是1的表示x与y不同的位,是0的表示相同的位。然后统计这个数字的二进制里面有多少个1就行了~

统计的时候每次把xor和1做与(&)运算,加到count里。因为规定了它们的最大值,所以循环最多32次,统计32位的情况。

代码:

class Solution {
    public int hammingDistance(int x, int y) {
        int xor = x ^ y;
        int count = 0;
        for(int i = 0; i < 32; i ++){
            count += xor & 1;
            xor = xor >> 1;
        }
        return count;
    }
}


三、别人的淫奇技巧

1. 用我没见过的函数……

public class Solution {
    public int hammingDistance(int x, int y) {
        return Integer.bitCount(x ^ y);
    }
}

2. 方法类似,短小精悍。。

public int hammingDistance(int x, int y) {
    int xor = x ^ y, count = 0;
    for (int i=0;i<32;i++) count += (xor >> i) & 1;
    return count;
}

3. 这个有点高端的样子

class Solution {
public:
    int hammingDistance(int x, int y) {
        int dist = 0, n = x ^ y;
        while (n) {
            ++dist;
            n &= n - 1;
        }
        return dist;
    }
};
看不懂啊,这是什么…引用大神的解答:

@jonvasquez1 Considering this example. Let's say n = 10101, and dist = 0 asccording to above code of @pengr7.

  • Before we go into the while loop. n = 10101, dist = 0
  • Loop 1.  dist = 1, n =10101 & 10100 = 10100
  • Loop 2.  dist = 2, n =10100 & 10011 = 10000
  • Loop 3.  dist = 3, n =10000 & (0)1111 = 0
  • Loop ends. dist = 3

The change of n :

  • 10101
  • 10100
  • 10000
  • 00000

Conclusion: n & (n-1) converts the right most 1 to 0 .
This is the key idea solving the problem. By counting how many times we can perform this operation, we know how many 1 exists in the binary representation of n

大概意思就是,n&(n-1)会把二进制最右边的1变成0。然后有几个1就能变成几个不为0的值。简直6666~差距吖

四、知识点

位运算。

参考博客:http://blog.csdn.net/xiaochunyong/article/details/7748713


五、碎碎念

对Java的位运算符不是特别熟悉。。继续加油~

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值