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

173

被折叠的 条评论
为什么被折叠?



