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 ≤ x, y < 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.

分析

"corresponding bits are different"即"异或"运算,Java中"异或运算符"的符号为^
(例:a的值是15,转换成二进制为1111;b的值是2,转换成二进制为0010。则a^b的结果为1101,即13。)
此题可转化为:求x异或y的结果的二进制表达式中'1'的个数

解答

解法1:(我)遍历二进制字符串(12ms)

将x异或y的结果转化为二进制字符串,遍历所有字符,求'1'的个数

public class Solution {
    public int hammingDistance(int x, int y){
        String str = Integer.toBinaryString(x ^ y);//或Integer.toString(x ^ y , 2)
        int count = 0;
        for (int i = 0; i < str.length(); i++){
            if (str.charAt(i) == '1'){
                count++;
            }
        }
        return count;
    }
}

 

解法2:求二进制字符串差值(18ms)

将x异或y的结果转化为二进制字符串,将其中所有"1"替换为""(空字符串),求替换前后字符串长度差值

public class Solution {
    public int hammingDistance(int x, int y){
        String str = Integer.toBinaryString(x ^ y);//或Integer.toString(x ^ y , 2)
        String str2 = str.replaceAll("1","");
        return str.length() - str2.length();
    }
}


解法3:使用系统内置函数Integer.bitCount()(24ms)

Integer.bitCount() 返回指定int值的二进制补码表示形式的1位的数量。例:Integer.bitCount(5) = 2,因为5的二进制补码表示为101,其中'1'的个数为2

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


解法4:位运算(>>, &)(11ms√)

计算xor & 1,若xor末位为1,结果为1;若xor末位为0,结果为0。将结果记入count。再将xor右移1位。重复上述过程,直到xor右移到尽头(xor == 0)
0101 ---> 010 ---> 01 ---> 0

public class Solution {
    public int hammingDistance(int x, int y){
        int xor = x ^ y;
        int count = 0;
        while (xor != 0){
            count += xor & 1;
            xor >>= 1;
        }
        return count;
    }
}

转载于:https://www.cnblogs.com/xuehaoyue/p/6412242.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值