首页 > 代码库 > LeetCode:461. Hamming Distance

LeetCode:461. Hamming Distance

 1 package BitManipulation;
 2 //Question 461. Hamming Distance
 3 /*
 4 The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
 5 Given two integers x and y, calculate the Hamming distance.
 6 Note:
 7 0 ≤ x, y < 231.
 8 Example:
 9 Input: x = 1, y = 4
10 Output: 2
11 Explanation:
12 1   (0 0 0 1)
13 4   (0 1 0 0)
14        ↑   ↑
15 The above arrows point to positions where the corresponding bits are different.
16  */
17 public class hammingDistance461 {
18     public static int hammingDistance(int x, int y) {
19         int count=0;
20         while(x>0|y>0){
21             count+=(x&1)^(y&1);
22             x=x>>1;
23             y=y>>1;
24         }
25         return count;
26     }
27     //test
28     public static void main(String[] args){
29         int x=1;
30         int y=4;
31         System.out.println(hammingDistance(x,y));
32     }
33     
34     //study the solution of other people
35     //example1:use Integer.bitCount
36     public static int hammingDistance1(int x, int y) {
37         return Integer.bitCount(x ^ y);
38     }
39     //example2:xor = (xor) & (xor-1)
40     //4(100),1(001)->101&100=100->100&011=000
41     //1000001001这样中间的0可以一步直接跳过,机智!
42     public int hammingDistance2(int x, int y) {
43         int count = 0;
44         for(int xor = x^y; xor != 0; xor = (xor) & (xor-1)) count++;
45         return count;
46     }
47 }

 

LeetCode:461. Hamming Distance