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; } }