LeetCode 题解工作台
汉明距离
两个整数之间的 汉明距离 指的是这两个数字对应二进制位不同的位置的数目。 给你两个整数 x 和 y ,计算并返回它们之间的汉明距离。 示例 1: 输入: x = 1, y = 4 输出: 2 解释: 1 (0 0 0 1) 4 (0 1 0 0) ↑ ↑ 上面的箭头指出了对应二进制位不同的位置。 示…
1
题型
6
代码语言
3
相关题
当前训练重点
简单 · 位运算·操作·driven·solution·strategy
答案摘要
我们将 和 按位异或,得到的结果中的 的个数就是汉明距离。 时间复杂度 ,空间复杂度 。
Interview AiBoxInterview AiBox 实时 AI 助手,陪你讲清 位运算·操作·driven·solution·strategy 题型思路
题目描述
两个整数之间的 汉明距离 指的是这两个数字对应二进制位不同的位置的数目。
给你两个整数 x 和 y,计算并返回它们之间的汉明距离。
示例 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. 转换数字的最少位翻转次数 相同。
解题思路
方法一:位运算
我们将 和 按位异或,得到的结果中的 的个数就是汉明距离。
时间复杂度 ,空间复杂度 。
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
return (x ^ y).bit_count()
复杂度分析
| 指标 | 值 |
|---|---|
| 时间 | Depends on the final approach |
| 空间 | Depends on the final approach |
面试官常问的追问
外企场景- 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.
常见陷阱
外企场景- 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.
进阶变体
外企场景- 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?