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;
    }
};
相关推荐
Wang20122013几秒前
AI各个领域适用的大模型介绍和适配的算法
人工智能·算法
Yzzz-F8 分钟前
CF GYM105316A DP
数据结构·算法
智算菩萨17 分钟前
迷宫生成算法:从生成树到均匀随机,再到工程化 Python 实现
python·算法·游戏
醒过来摸鱼20 分钟前
《线性空间》专栏写作计划(目录)
算法
C雨后彩虹20 分钟前
幼儿园分班
java·数据结构·算法·华为·面试
Yupureki24 分钟前
《算法竞赛从入门到国奖》算法基础:入门篇-二分算法
c语言·开发语言·数据结构·c++·算法·visual studio
游戏23人生29 分钟前
c++ 语言教程——16面向对象设计模式(五)
开发语言·c++·设计模式
qq_4634084231 分钟前
React Native跨平台技术在开源鸿蒙中使用WebView来加载鸿蒙应用的网页版或通过一个WebView桥接本地代码与鸿蒙应用
javascript·算法·react native·react.js·开源·list·harmonyos
老王熬夜敲代码31 分钟前
C++的decltype
开发语言·c++·笔记
Jul1en_31 分钟前
【算法】位运算
算法