题目
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:
Example
The above arrows point to positions where the corresponding bits are different.
解
class Solution {
public int hammingDistance(int x, int y) {
int h=0;
ArrayList<Integer> rx=new ArrayList<Integer>();
ArrayList<Integer> ry=new ArrayList<Integer>();
while(x/2!=0){
rx.add(x%2);
x=x/2;
}
if(x%2!=0) rx.add(x%2);
while(y/2!=0){
ry.add(y%2);
y=y/2;
}
if(y%2!=0) ry.add(y%2);
int sizeX=rx.size();
int sizeY=ry.size();
int i=0;
int j=0;
while(i<sizeX && j<sizeY){
Integer A=rx.get(i);
Integer B=ry.get(j);
if(!A.equals(B)){
h++;
}
i++;
j++;
}
if(i==sizeX){
while(j<sizeY){
if(ry.get(j).equals(1)){
h++;
}
j++;
}
}else{
while(i<sizeX){
if(rx.get(i).equals(1)){
h++;
}
i++;
}
}
return h;
}
}
更简单的解法
//解法1
public class Solution {
public int hammingDistance(int x, int y) {
return Integer.bitCount(x ^ y);
}
}
//解法2
public class Solution {
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;
}
}
本文介绍了两种计算两个整数间汉明距离的有效方法。汉明距离是指两个整数对应的二进制位中不同位的数量。文章首先提供了一种通过转换整数为二进制并比较每一位来计算汉明距离的方法;随后提出了一种更简洁的方法,利用异或运算和bitCount函数直接得出结果。
372

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



