Leetcode 461: Hamming Distance

该博客介绍了一个计算两个整数汉明距离的算法。通过将十进制数转换为二进制字符串,然后对齐它们的长度并逐位比较,可以计算出不同位的数量,即汉明距离。提供的代码实现了这一过程,具有O(n)的时间复杂度,其中n是较长二进制字符串的长度。

问题描述:
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, return the Hamming distance between them.
例如: 1: 0001
4: 0100
以上两个数在两个位置上不同,故hamming distance=2

思路:
我考虑把十进制数转换为二进制字符串,所以涉及字符串长度问题,为了避免分类讨论谁的长度长,我们在程序最开始规定x>=y,否则交换x,y(确保交换xy不影响结果)
然后转化为二进制字符串
然后补齐:先计算长度差,在较短的(这里肯定是y更短或等长)前面补0
然后遍历并计数

代码如下:

 class Solution {
    public int hammingDistance(int x, int y) {
        //assume x>=y, otherwise swap
        if(x<y){
            return hammingDistance(y,x);
        }
        //convert x and y to binary string
        String str_x=Integer.toBinaryString(x);
        String str_y=Integer.toBinaryString(y);
        //str_x and str_y might not equal in length, if not , make them same
        int diff=str_x.length()-str_y.length();
        while(diff>0){
            str_y="0"+str_y;
            diff--;
        }
        //now, str_x and str_y should have the same length, now le's comapre them!
        int counter=0;
        for(int i=0; i<str_x.length(); i++){
            if(str_x.charAt(i)!=str_y.charAt(i)){
                counter++;
            }
        }
        return counter;
    }
}

时间复杂度: O(n), n is the size of the longer binary string

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值