LeetCode

来源:互联网 发布:怎么关掉电脑445端口 编辑:程序博客网 时间:2024/06/05 14:57

题目

汉明距离-百度百科

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.

思路

  将两个数异或,求出异或后二进制中1的位数。

代码

public int hammingDistance(int x, int y) {    int res = 0;    // 异或    int tmp = x ^ y;    // 每次将 tmp 和 tmp - 1 相与    // 如 0101 & 0100 = 0100    //    0100 & 0011 = 0000    // 相当于每次去除了一个1    while (tmp > 0) {        res++;        tmp = tmp & (tmp - 1);    }    return res;}