力扣-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;
    }
};
相关推荐
格林威1 小时前
常规线扫描镜头有哪些类型?能做什么?
人工智能·深度学习·数码相机·算法·计算机视觉·视觉检测·工业镜头
程序员莫小特3 小时前
老题新解|大整数加法
数据结构·c++·算法
过往入尘土4 小时前
服务端与客户端的简单链接
人工智能·python·算法·pycharm·大模型
zycoder.4 小时前
力扣面试经典150题day1第一题(lc88),第二题(lc27)
算法·leetcode·面试
Dream it possible!4 小时前
LeetCode 面试经典 150_哈希表_存在重复元素 II(46_219_C++_简单)
leetcode·面试·散列表
蒙奇D索大4 小时前
【数据结构】考研数据结构核心考点:二叉排序树(BST)全方位详解与代码实现
数据结构·笔记·学习·考研·算法·改行学it
智驱力人工智能5 小时前
工厂抽烟检测系统 智能化安全管控新方案 加油站吸烟检测技术 吸烟行为智能监测
人工智能·算法·安全·边缘计算·抽烟检测算法·工厂抽烟检测系统·吸烟监测
学学学无无止境5 小时前
组合两个表-力扣
leetcode
程序员爱钓鱼5 小时前
Go语言实战案例——进阶与部署篇:编写Makefile自动构建Go项目
后端·算法·go
_Power_Y6 小时前
Java面试常用算法api速刷
java·算法·面试