LeetCode461. Hamming Distance

文章目录

一、题目

The Hamming distance between two integers is the number of positions at which the corresponding bits are different.

Given two integers x and y, return the Hamming distance between them.

Example 1:

Input: x = 1, y = 4

Output: 2

Explanation:

1 (0 0 0 1)

4 (0 1 0 0)

↑ ↑

The above arrows point to positions where the corresponding bits are different.

Example 2:

Input: x = 3, y = 1

Output: 1

Constraints:

0 <= x, y <= 231 - 1

二、题解

cpp 复制代码
class Solution {
public:
    int hammingDistance(int x, int y) {
        int n = x ^ y;
        //计算n中1的个数
        n = (n & 0x55555555) + ((n >> 1) & 0x55555555);
        n = (n & 0x33333333) + ((n >> 2) & 0x33333333);
        n = (n & 0x0f0f0f0f) + ((n >> 4) & 0x0f0f0f0f);
        n = (n & 0x00ff00ff) + ((n >> 8) & 0x00ff00ff);
        n = (n & 0x0000ffff) + ((n >> 16) & 0x0000ffff);
        return n;
    }
};
相关推荐
徐小夕1 小时前
开源!我用SQLite + DuckDB打造了一款可视化AI问数平台
前端·算法·github
Hrain-AI2 小时前
2026 企业 AI 智能体平台横评:8 大主流平台 7 维度实测对比
人工智能·算法·机器学习
Angel Q.2 小时前
因子分析和生成模型有什么关系?从“幕后因素”到“生成数据”
算法
888CC++3 小时前
C语言与C++的区别:从面向过程到面向对象
java·c语言·c++
FBI HackerHarry浩4 小时前
AI大模型开发V2第四阶段线性回归
人工智能·算法·线性回归
Darkwanderor4 小时前
Linux系统编程实战项目:模拟实现shell
linux·c++
himobrinehacken4 小时前
揭秘Windows程序启动的神秘之旅
c++·安全
Jerry5 小时前
LeetCode 108. 将有序数组转换为二叉搜索树
算法
库玛西5 小时前
C++ 运行时多态 :核心总结与原理图解
c语言·c++·笔记