力扣-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;
    }
};
相关推荐
弥彦_9 分钟前
cf1925B&C
数据结构·算法
YuTaoShao30 分钟前
【LeetCode 热题 100】994. 腐烂的橘子——BFS
java·linux·算法·leetcode·宽度优先
Wendy14418 小时前
【线性回归(最小二乘法MSE)】——机器学习
算法·机器学习·线性回归
拾光拾趣录8 小时前
括号生成算法
前端·算法
渣呵9 小时前
求不重叠区间总和最大值
算法
拾光拾趣录9 小时前
链表合并:双指针与递归
前端·javascript·算法
好易学·数据结构9 小时前
可视化图解算法56:岛屿数量
数据结构·算法·leetcode·力扣·回溯·牛客网
香蕉可乐荷包蛋10 小时前
AI算法之图像识别与分类
人工智能·学习·算法
chuxinweihui11 小时前
stack,queue,priority_queue的模拟实现及常用接口
算法
tomato0911 小时前
河南萌新联赛2025第(一)场:河南工业大学(补题)
c++·算法