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.

PS:求海明距离。

思路:就是求x和y二进制的异或中的1的个数

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
public  class  Solution {
     public  int  hammingDistance( int  x,  int  y) {
         // String x1=Integer.toBinaryString(x);
         // String y1=Integer.toBinaryString(y);
         int  tem=x^y;
         int  count= 0 ;
         String str=Integer.toBinaryString(tem);
         for ( int  i= 0 ;i<str.length();i++){
             if (str.charAt(i)== '1' ){
                 count++;
             }
         }
         // System.out.println(count);
         
         return  count;
     }
}