LeetCode:461. Hamming Distance

本文介绍了一种计算两个整数间汉明距离的方法。通过三种不同的实现方式对比,展示了位操作符在解决此类问题上的应用技巧。包括逐位比较、利用Integer.bitCount()以及通过异或操作减少计算步骤。
 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 }

 

转载于:https://www.cnblogs.com/luluqiao/p/6255111.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值