力扣-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;
    }
};
相关推荐
千金裘换酒2 小时前
LeetCode 移动零元素 快慢指针
算法·leetcode·职场和发展
wm10432 小时前
机器学习第二讲 KNN算法
人工智能·算法·机器学习
NAGNIP2 小时前
一文搞懂机器学习线性代数基础知识!
算法
NAGNIP2 小时前
机器学习入门概述一览
算法
iuu_star3 小时前
C语言数据结构-顺序查找、折半查找
c语言·数据结构·算法
Yzzz-F3 小时前
P1558 色板游戏 [线段树 + 二进制状态压缩 + 懒标记区间重置]
算法
漫随流水3 小时前
leetcode算法(515.在每个树行中找最大值)
数据结构·算法·leetcode·二叉树
mit6.8244 小时前
dfs|前后缀分解
算法
扫地的小何尚4 小时前
NVIDIA RTX PC开源AI工具升级:加速LLM和扩散模型的性能革命
人工智能·python·算法·开源·nvidia·1024程序员节
千金裘换酒5 小时前
LeetCode反转链表
算法·leetcode·链表