⭐算法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 的最大值。

相关推荐
会飞的拖把4 分钟前
Python序列详解:列表、元组、字符串的通用操作(超详细版)
开发语言·windows·python
2402_882893866 分钟前
用哈希表封装 unordered_map 和 unordered_set —— 手撕 C++ 哈希容器
c++·哈希桶·unordered_map·unordered_set
不会就选b14 分钟前
算法日常・每日刷题--<贪心>5
算法
熊猫钓鱼>_>17 分钟前
用 OHAudioSuite 空间渲染节点搭一座「3D 有声博物馆」——从三种模式到 FreeBuds 头追的实战记录
c++·3d·ai·harmonyos·arkts·audio·ohaudiosuite
reasonsummer24 分钟前
【办公类-115-01】20260906育儿知识(家园小报)批量制作(2026年9月-2027年6月)
开发语言·数据库·c#
君顾124 分钟前
智慧场馆解决方案小程序系统实战:从架构设计到上线指南
java·开发语言·智慧场馆
zhougl99625 分钟前
Dockerfile实战教程
java·开发语言·spring boot
FfHUCisI33 分钟前
Golang 网络轮询器 netpoll:把阻塞 IO 变成事件通知
开发语言·网络·golang
XiaoQiao66699933 分钟前
C 语言常用头文件及里面核心函数
c语言·开发语言
_约书亚_34 分钟前
chapter 9 高级线程管理 — 归纳总结
c++