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;
    }
};
相关推荐
不吃土豆的马铃薯5 分钟前
Spdlog 入门:日志记录器与日志槽基础详解
服务器·开发语言·c++·c·日志·spdlog
此生决int9 分钟前
算法从入门到精通——前缀和
c++·算法·蓝桥杯
我星期八休息14 分钟前
Linux系统编程—库制作与原理
linux·运维·服务器·数据结构·人工智能·python·散列表
大大杰哥26 分钟前
leetcode hot100(4)矩阵
算法·leetcode·矩阵
Fuyo_111929 分钟前
C++中的活字印刷术——模板·初阶
开发语言·c++·笔记
小白|30 分钟前
cmake:昇腾CANN构建系统完全指南
java·c++·算法
nebula-AI30 分钟前
人工智能导论:模型与算法(未来发展与趋势)
人工智能·神经网络·算法·机器学习·量子计算·automl·类脑计算
王老师青少年编程31 分钟前
2026年全国青少年信息素养大赛“算法应用主题赛”(初赛)【C++考点大纲】(全场景、组别):文末附备考秘籍!
c++·全国青少年信息素养大赛·初赛·2026年·算法应用主题赛·考点大纲
炽烈小老头32 分钟前
【每天学习一点算法 2026/05/21】课程表
学习·算法
Season45034 分钟前
C++之模板元编程(前置知识 constexpr)
开发语言·c++