题目链接:https://leetcode-cn.com/problems/hamming-distance/
题目如下:
class Solution {
public int hammingDistance(int x, int y) {
int len,count=0;
List<Integer> array1=new ArrayList<Integer>();
List<Integer> array2=new ArrayList<Integer>();
//若输入1,4;则得1:[1],4:[0,0,1]
intobinary(x,array1);
intobinary(y,array2);
int i=0,j=0;
while(i<array1.size()&&j<array2.size())
if(array1.get(i++)!=array2.get(j++)) count++;
while(i<array1.size())
if(array1.get(i++)==1) count++;//默认其他位置均为0
while(j<array2.size())
if(array2.get(j++)==1) count++;
//System.out.println(array1);//用于查看当前arraylist里的内容
//System.out.println(array2);
return count;
}
public void intobinary(int num,List<Integer> array){
while(num!=0){
array.add(num%2);
num=num/2;
}
}
}