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;
    }
};
相关推荐
ZPC82107 小时前
docker 镜像备份
人工智能·算法·fpga开发·机器人
ZPC82107 小时前
docker 使用GUI ROS2
人工智能·算法·fpga开发·机器人
琢磨先生David7 小时前
Day1:基础入门·两数之和(LeetCode 1)
数据结构·算法·leetcode
哇哈哈20217 小时前
信号量和信号
linux·c++
颜酱7 小时前
栈的经典应用:从基础到进阶,解决LeetCode高频栈类问题
javascript·后端·算法
多恩Stone8 小时前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
生信大杂烩8 小时前
癌症中的“细胞邻域“:解码肿瘤微环境的空间密码 ——Nature Cancer 综述解读
人工智能·算法
蜡笔小马8 小时前
21.Boost.Geometry disjoint、distance、envelope、equals、expand和for_each算法接口详解
c++·算法·boost
m0_531237178 小时前
C语言-数组练习进阶
c语言·开发语言·算法
qq_454245038 小时前
基于组件与行为的树状节点系统
数据结构·c#