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;
    }
};
相关推荐
朔北之忘 Clancy5 分钟前
第一章 顺序结构程序设计(1)
c++·算法·青少年编程·竞赛·教材·考级·讲义
老鼠只爱大米11 分钟前
LeetCode经典算法面试题 #41:缺失的第一个正数(位置交换法、标记法等多种方法详解)
算法·leetcode·原地哈希·缺失的第一个正数·算法面试·位图法·集合哈希法
星火开发设计14 分钟前
变量与常量:C++ 中 const 关键字的正确使用姿势
开发语言·c++·学习·const·知识
hetao173383720 分钟前
2026-01-14~15 hetao1733837 的刷题笔记
c++·笔记·算法
好奇龙猫21 分钟前
【大学院-筆記試験練習:线性代数和数据结构(10)】
数据结构·线性代数
百度搜不到…21 分钟前
背包问题递推公式中的dp[j-nums[j]]到底怎么理解
算法·leetcode·动态规划·背包问题
一起养小猫39 分钟前
LeetCode100天Day13-移除元素与多数元素
java·算法·leetcode
a***592643 分钟前
C++跨平台开发:挑战与解决方案
开发语言·c++
ACERT3331 小时前
10.吴恩达机器学习——无监督学习01聚类与异常检测算法
python·算法·机器学习
诗词在线1 小时前
从算法重构到场景复用:古诗词数字化的技术破局与落地实践
python·算法·重构