力扣-461.汉明距离

Method 1

直接比较x,y二进制中的每一位,如果不同则cnt加一,并且x,y每次右移一位

cpp 复制代码
class Solution {
public:
    int hammingDistance(int x, int y) {
        int cnt = 0;
        while(x > 0 && y > 0) {
            if((x & 1) != (y & 1)) cnt++;
            x >>= 1;
            y >>= 1;
        }
        while(x > 0) {
            if(x & 1) cnt++;
            x >>= 1;
        }
        while(y > 0) {
            if(y & 1) cnt++;
            y >>= 1;
        }
        return cnt;
    }
};

Method 2

使用异或运算,当二进制位相同时为1,不同时为0

cpp 复制代码
class Solution {
public:
    int hammingDistance(int x, int y) {
        int cnt = 0;
        int s = x ^ y;
        while(s > 0) {
            cnt += s & 1;
            s >>= 1;
        }
        return cnt;
    }
};
相关推荐
蒙奇D索大14 分钟前
【算法】递归算法的深度实践:从布尔运算到二叉树剪枝的DFS之旅
笔记·学习·算法·leetcode·深度优先·剪枝
卡提西亚1 小时前
C++笔记-25-函数模板
c++·笔记·算法
ghie90901 小时前
MATLAB/Simulink水箱水位控制系统实现
开发语言·算法·matlab
多多*1 小时前
分布式系统中的CAP理论和BASE理论
java·数据结构·算法·log4j·maven
yuan199972 小时前
基于粒子群优化(PSO)算法的PID控制器参数整定
算法
小白程序员成长日记2 小时前
2025.11.10 力扣每日一题
数据结构·算法·leetcode
hoiii1872 小时前
基于交替方向乘子法(ADMM)的RPCA MATLAB实现
人工智能·算法·matlab
fengfuyao9853 小时前
MATLAB的加权K-means(Warp-KMeans)聚类算法
算法·matlab·kmeans
循环过三天3 小时前
3.1、Python-列表
python·算法
dragoooon344 小时前
[优选算法专题六.模拟 ——NO.40~41 外观数列、数青蛙]
数据结构·算法·leetcode