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;
    }
};
相关推荐
hmcjn(小何同学)几秒前
轻松Linux-9.进程间通信
linux·运维·服务器·c++·bash
久菜盒子工作室16 分钟前
量化金融|基于算法和模型的预测研究综述
算法·金融
云泽80819 分钟前
数据结构之单链表和环形链表的应用(二)-
数据结构
落羽的落羽23 分钟前
【C++】C++11的包装器:function与bind简介
c++·学习
打不了嗝 ᥬ᭄28 分钟前
【Linux】线程概念与控制
linux·c++
CoovallyAIHub1 小时前
SBP-YOLO:面向嵌入式悬架的轻量实时模型,实现减速带与坑洼高精度检测
深度学习·算法·计算机视觉
UnnamedOrange1 小时前
ROS1 配置代码覆盖率
c++·cmake
沐怡旸1 小时前
【底层机制】std::unordered_map 扩容机制
c++·面试
沐怡旸1 小时前
【底层机制】auto 关键字的底层实现机制
c++·面试
CoovallyAIHub1 小时前
医药、零件、饮料瓶盖……SuperSimpleNet让质检“即插即用”
深度学习·算法·计算机视觉