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;
    }
};
相关推荐
wabs6661 天前
关于贪心算法的思考
算法·贪心算法
社交怪人1 天前
【判断大小】信息学奥赛一本通C语言解法(题号1043)
算法
Snasph1 天前
GNU Make 用户手册(中文版)
服务器·算法·gnu
江澎涌1 天前
拆解与 AI 的一次对话
人工智能·算法·程序员
sheeta19981 天前
LeetCode 每日一题笔记 日期:2026.06.02 题目:3635. 最早完成陆地和水上游乐设施的时间 II
笔记·算法·leetcode
Lsk_Smion1 天前
力扣实训 _ [102].层序遍历--前序--后续_递归与非递归的实现
数据结构·算法·leetcode
Lsk_Smion1 天前
力扣实训 _ [25].K个一组链表
数据结构·链表
小欣加油1 天前
leetcode3751 范围内总波动值I
java·数据结构·c++·算法·leetcode
代码中介商1 天前
C++左值与右值:核心判断法则详解
开发语言·c++
玖玥拾1 天前
C/C++ 基础笔记(七)
c语言·c++