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;
    }
};
相关推荐
致Great1 小时前
Pi 的上下文压缩,到底是怎么工作的?
算法
wuyk5552 小时前
4.树:一对多的层次数据结构
开发语言·数据结构·stm32·单片机
watersink2 小时前
机器学习聚类算法
算法·机器学习·聚类
luj_17683 小时前
桥牌思维启示:系统设计的模块化架构
c语言·开发语言·c++·经验分享·算法
会周易的程序员4 小时前
aiDgePLC iec61131 虚拟机 完整使用文档
c++·物联网·架构·st·iec61131
小小龙学IT4 小时前
Boost.Beast 深度实战:基于 Asio 的开源 C++ HTTP/WebSocket 协议库
c++·websocket·http
饼饼学习空间智能5 小时前
家庭服务机器人训练数据怎么积累?仿真、真实采集与持续学习的技术路线分析
人工智能·算法·机器学习
不可求~5 小时前
C++ std::string_view 不是字符串:从悬空引用到安全用法
java·开发语言·c++
en.en..6 小时前
数据结构考点解析:逻辑闭环与存储循环辨析
数据结构