【跟Leon一起刷LeetCode】461. Hamming Distance

Hamming Distance

Description:

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integersx and y, calculate the Hamming distance.

Note:

0 ≤x, y < 2^31.

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.
问题描述:

两个数之间的汉明距离就是求出这两个数字的二进制位数不同的个数。比如上面的1和4,在第0位和第2位数字不同,因此1和4的汉明距离就是2。

Solution:

依据题意可以有一种效率不是那么高的方法:将两个数转换成二进制数,逐位进行比较。
里面会牵扯到类型的转换,会比较麻烦,在这不贴出相应代码。

为了去掉麻烦的类型转换,引入逻辑运算符:异或。

class Solution {
    public int hammingDistance(int x, int y) {
        int d = 0;
        int bitxor = x ^ y;

        while (bitxor > 0){
            if (bitxor % 2 == 1){
                d++;
            }
            bitxor = bitxor >> 1;
        }

        return d;
    }
}

先将两个数进行异或运算,得到结果,再去数1的个数。

逐位去数1的个数显然不是那么优雅,找了下Java API,找了个专门的函数,代码可简化成如下:

class Solution {
    public int hammingDistance(int x, int y) {
        return Integer.bitCount(x ^ y);
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值