he 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.
Note:
0 ≤ x, y < 231.
Example:
Input: x = 1, y = 4 Output: 2 Explanation: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ The above arrows point to positions where the corresponding bits are different./** * Created by Administrator on 2017/1/26. */ public class Test { public static void main(String[] args) { System.out.println(hammingDistance(5, 7)); } public static int hammingDistance(int x, int y) { int xor = x ^ y; //异或操作在结果中将不同的数那一位置为1,然后最后统计1的个数 System.out.println(xor); int dis = 0; for (int i = 0; i < 32; i++) { dis += (xor >> i) & 1; } return dis; } }
本文介绍了一种计算两个整数之间汉明距离的方法。通过使用异或操作找出不同位的数量,进而计算出两个整数二进制表示中对应位不同的数量。
727

被折叠的 条评论
为什么被折叠?



