力扣-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;
    }
};
相关推荐
CoderCodingNo几秒前
【GESP】C++五级真题(数论, 贪心思想考点) luogu-B4070 [GESP202412 五级] 奇妙数字
开发语言·c++·算法
百***58846 分钟前
MATLAB高效算法实战技术文章大纲1
人工智能·算法·matlab
hans汉斯26 分钟前
【人工智能与机器人研究】自动移液设备多轴运动控制系统设计
算法·机器学习·3d·自然语言处理·机器人·硬件架构·汉斯出版社
guygg8835 分钟前
经典信道估计MATLAB实现(含LSMMSE算法)
深度学习·算法·matlab
foundbug9991 小时前
最小二乘支持向量机(LSSVM)回归的解析
算法·支持向量机·回归
程芯带你刷C语言简单算法题1 小时前
Day43~实现一个算法求一个数字的树根
c语言·开发语言·算法·c
柳鲲鹏2 小时前
关于#pragma pack(push, 8),DeepSeek回答错误
算法
settingsun12252 小时前
【AI-算法-01】ResNet (残差网络) & Skip Connections
人工智能·算法
橘颂TA2 小时前
【剑斩OFFER】算法的暴力美学——两数之和
数据结构·算法·leetcode·力扣·结构与算法
福楠2 小时前
C++ STL | vector
开发语言·c++·算法