LeetCode 题解工作台

汉明距离

两个整数之间的 汉明距离 指的是这两个数字对应二进制位不同的位置的数目。 给你两个整数 x 和 y ,计算并返回它们之间的汉明距离。 示例 1: 输入: x = 1, y = 4 输出: 2 解释: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ 上面的箭头指出了对应二进制位不同的位置。 示…

category

1

题型

code_blocks

6

代码语言

hub

3

相关题

当前训练重点

简单 · 位运算·操作·driven·solution·strategy

bolt

答案摘要

我们将 和 按位异或,得到的结果中的 的个数就是汉明距离。 时间复杂度 ,空间复杂度 。

Interview AiBox logo

Interview AiBox 实时 AI 助手,陪你讲清 位运算·操作·driven·solution·strategy 题型思路

试试 AiBox 面试助手arrow_forward
description

题目描述

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

给你两个整数 xy,计算并返回它们之间的汉明距离。

 

示例 1:

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

示例 2:

输入:x = 3, y = 1
输出:1

 

提示:

  • 0 <= x, y <= 231 - 1

 

注意:本题与 2220. 转换数字的最少位翻转次数 相同。

lightbulb

解题思路

方法一:位运算

我们将 xxyy 按位异或,得到的结果中的 11 的个数就是汉明距离。

时间复杂度 O(1)O(1),空间复杂度 O(1)O(1)

1
2
3
4
class Solution:
    def hammingDistance(self, x: int, y: int) -> int:
        return (x ^ y).bit_count()
speed

复杂度分析

指标
时间Depends on the final approach
空间Depends on the final approach
psychology

面试官常问的追问

外企场景
  • question_mark

    Look for a candidate’s understanding of bitwise operations like XOR.

  • question_mark

    Check if the candidate can implement bit counting techniques like Brian Kernighan’s algorithm.

  • question_mark

    Assess if the candidate can explain and optimize bit manipulation techniques for clarity and efficiency.

warning

常见陷阱

外企场景
  • error

    Candidates may use inefficient methods such as converting integers to binary strings and counting differences, which is slower.

  • error

    Failure to understand how to properly count set bits in the XOR result can lead to incorrect results.

  • error

    Candidates may overlook optimizations such as Brian Kernighan’s algorithm and default to slower iterative methods.

swap_horiz

进阶变体

外企场景
  • arrow_right_alt

    What if the integers are represented in a different number of bits?

  • arrow_right_alt

    How would you modify your approach for signed integers?

  • arrow_right_alt

    Can you optimize further for large input ranges?

help

常见问题

外企场景

汉明距离题解:位运算·操作·driven·solution·… | LeetCode #461 简单