码迷,mamicode.com
首页 > 其他好文 > 详细

LeetCode:461. Hamming Distance

时间:2017-01-06 10:57:34      阅读:201      评论:0      收藏:0      [点我收藏+]

标签:osi   blog   int   input   res   nbsp   exp   pack   main   

 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

标签:osi   blog   int   input   res   nbsp   exp   pack   main   

原文地址:http://www.cnblogs.com/luluqiao/p/6255111.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!