LeetCode 461. 汉明距离

    技术2022-07-11  111

    目录结构

    1.题目

    2.题解

    2.1内置位计数功能

    2.2移位

    2.3布赖恩·克尼根算法


    1.题目

    两个整数之间的汉明距离指的是这两个数字对应二进制位不同的位置的数目。

    给出两个整数 x 和 y,计算它们之间的汉明距离。

    注意:

    示例:

    输入: x = 1, y = 4 输出: 2 解释: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ 上面的箭头指出了对应二进制位不同的位置。

    来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/hamming-distance 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。

    2.题解

    2.1内置位计数功能

    Integer.bitCount()函数:统计整数的二进制表达中1的个数。 public class Solution461 { public int hammingDistance(int x, int y) { return Integer.bitCount(x ^ y); } }

    2.2移位

    右移位:每个位置都会被移动到最右边。移位后检查最右位的位是否为 1 。 public class Solution461 { public int hammingDistance(int x, int y) { int xor = x ^ y; int result = 0; while (xor != 0) { if (xor % 2 == 1) { result++; } xor >>= 1; } return result; } } 时间复杂度:空间复杂度:

    2.3布赖恩·克尼根算法

    该算法使用特定比特位和算术运算移除等于 1 的最右比特位。

    示例:

    x = 10001000 x-1 = 10000111 x&(x-1) = 10000000 public class Solution461 { public int hammingDistance(int x, int y) { int xor = x ^ y; int result = 0; while (xor != 0) { result++; xor &= (xor - 1); } return result; } } 时间复杂度:空间复杂度:

    参考官方题解

    作者:LeetCode 链接:https://leetcode-cn.com/problems/hamming-distance/solution/yi-ming-ju-chi-by-leetcode/ 来源:力扣(LeetCode) 著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

     

     

    Processed: 0.108, SQL: 9