⭐算法OJ⭐汉明距离【位操作】(C++ 实现)Hamming Distance

Hamming Distance(汉明距离)是用于衡量两个等长字符串在相同位置上不同字符的个数的度量。它通常用于比较两个二进制字符串或编码序列的差异。

定义

给定两个长度相同的字符串 A A A 和 B B B,它们的汉明距离 D ( A , B ) D(A,B) D(A,B) 是在相同位置上字符不同的位置的数量。

示例

  1. 二进制字符串:
    • A=1011101
    • B=1001001
    • 汉明距离 D ( A , B ) = 2 D(A,B)=2 D(A,B)=2(第3位和第5位不同)。
  2. 字符串:
    • A="karolin"
    • B="kathrin"
    • 汉明距离 D ( A , B ) = 3 D(A,B)=3 D(A,B)=3(第3、4、5位不同)。

应用

  • 错误检测与纠正:在通信和编码理论中,汉明距离用于检测和纠正数据传输中的错误。
  • 生物信息学:用于比较 DNA 序列的相似性。
  • 机器学习:在分类算法中,用于计算样本之间的距离。

计算步骤

  • 比较两个字符串的每一位。
  • 统计不同位的数量。
  • 返回统计结果作为汉明距离。

公式

对于长度为 n n n 的两个字符串 A A A 和 B B B,汉明距离为:
D ( A , B ) = ∑ i = 1 n δ ( A i , B i ) D(A,B)= ∑_{i=1}^n δ(A_i ,B_i) D(A,B)=i=1∑nδ(Ai,Bi)

其中, δ ( A i , B i ) δ(A_i ,B_i ) δ(Ai,Bi) 是指示函数,当 A i ≠ B i A_i \neq B_i Ai=Bi 时为1,否则为0。

461. Hamming Distance

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, return the Hamming distance between them.

Example 1:

复制代码
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.

Example 2:

复制代码
Input: x = 3, y = 1
Output: 1

C++ 实现

cpp 复制代码
int hammingDistance(int x, int y) {
    int xor_result = x ^ y;  // 异或操作
    int distance = 0;
    
    // 统计 xor_result 中 1 的个数
    while (xor_result != 0) {
        distance += xor_result & 1;  // 检查最低位是否为 1
        xor_result >>= 1;  // 右移一位
    }
    
    return distance;
}

复杂度分析

这个算法的时间复杂度为 O ( l o g   n ) O(log\, n) O(logn),其中 n n n 是 xy 的最大值。

相关推荐
m0_531237179 分钟前
C语言-操作符进阶
c语言·开发语言
阿里云大数据AI技术11 分钟前
阿里云PAI助力新一代Qwen3.5模型发布!
人工智能·算法
q12345678909823 分钟前
FNN sin predict
开发语言·python
沐知全栈开发26 分钟前
C++ 多态
开发语言
小白菜又菜30 分钟前
Leetcode 221. Maximal Square
算法·leetcode·职场和发展
zihan032131 分钟前
若依(RuoYi)框架核心升级:全面适配 SpringData JPA,替换 MyBatis 持久层方案
java·开发语言·前端框架·mybatis·若依升级springboot
先做个垃圾出来………36 分钟前
Python字节串“b“前缀
开发语言·python
流云鹤1 小时前
牛客周赛Round 132(无F)
算法
Lee川1 小时前
深入解析:从内存模型到作用域陷阱——JavaScript变量的前世今生
javascript·算法