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;
    }
};
相关推荐
All for pursuit.5 小时前
【回溯-2】22.括号生成
数据结构·c++·算法·leetcode
longlongzihan5 小时前
LeetCode 1004.最大连续1的个数III 滑动窗口及动态规划题解
c++·算法·leetcode·dp·滑动窗口
朝朝辞暮i5 小时前
C++ 第 22 课:const —— 不允许随便修改的数据
开发语言·c++·算法
蒸蒸yyyyzwd6 小时前
力扣二分总结-lowerbound
c++
Chen—LSN6 小时前
数据结构——拿捏复杂度
java·c语言·开发语言·数据结构·经验分享·笔记·算法
Chen_harmony6 小时前
六、排序详解
c语言·数据结构·算法·排序算法
ShineWinsu6 小时前
对于Redis:List类型的解析
数据库·c++·redis·链表·缓存·面试·list
-dzk-6 小时前
【贪心算法】LC 55.跳跃游戏
算法·游戏·贪心算法
ofoxcoding6 小时前
Jev 模型评测深度解析:核心得分、能力局限与最佳适用任务场景
人工智能·算法·机器学习·ai
Evand J6 小时前
【MATLAB例程】三维A*路径规划与TOA-AOA-TDOA融合定位算法。附下载链接
数据库·算法·matlab