解题思路:
思路一:
(1)将两个数字分别转化为二进制,并分别用字符串表示
(2)将(1)得到的两个字符串转成长度相等的字符串,即字符串较短的进行补0操作
(3)依次遍历,查找字符串中每一位是1的有多少个
代码实现如下:
class Solution {
public int hammingDistance(int x, int y) {
String str1=toBinary(x);
String str2=toBinary(y);
int len1=str1.length();
int len2=str2.length();
int max=len1>len2?len1:len2;
int minus=Math.abs(len1-len2);
int cnt=0;
String temp="";
for(int i=0;i<minus;++i){
temp+=0;
}
if(len1<len2){
str1=temp+str1;
}
else{
str2=temp+str2;
}
for(int i=0;i<max;++i){
if(str1.charAt(i)!=str2.charAt(i)){
cnt++;
}
}
return cnt;
}
public String toBinary(int num){
String res="";
String result="";
if(num==0){
res+="0";
return res;
}
while(num!=0){
int temp=num%2;
res+=temp;
num=num>>1;
}
int len=res.length();
for(int i=len-1;i>=0;--i){
result+=res.charAt(i);
}
return result;
}
}
思路二:
(1)将两个数进行异或操作
(2)将异或后的数字用二进制表示
(3)查找(2)中每一位是1的个数
class Solution {
public int hammingDistance(int x, int y) {
int minus=x^y;
int cnt=0;
while(minus!=0){
int temp=minus%2;
if(temp==1){
cnt++;
}
minus=minus>>1;
}
return cnt;
}
}