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;
    }
};
相关推荐
吴维炜33 分钟前
「Python算法」计费引擎系统SKILL.md
python·算法·agent·skill.md·vb coding
No0d1es41 分钟前
电子学会青少年软件编程(C语言)等级考试试卷(三级)2025年12月
c语言·c++·青少年编程·电子学会·三级
Σίσυφος19002 小时前
PCL Point-to-Point ICP详解
人工智能·算法
you-_ling2 小时前
数据结构:4.二叉树
数据结构
bjxiaxueliang2 小时前
一文掌握C/C++命名规范:风格、规则与实践详解
c语言·开发语言·c++
玄〤2 小时前
Java 大数据量输入输出优化方案详解:从 Scanner 到手写快读(含漫画解析)
java·开发语言·笔记·算法
weixin_395448912 小时前
main.c_cursor_0202
前端·网络·算法
senijusene2 小时前
数据结构与算法:队列与树形结构详细总结
开发语言·数据结构·算法
青桔柠薯片2 小时前
数据结构:队列,二叉树
数据结构
杜家老五2 小时前
综合实力与专业服务深度解析 2026北京网站制作公司六大优选
数据结构·算法·线性回归·启发式算法·模拟退火算法