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;
    }
};
相关推荐
linux kernel6 分钟前
第七讲:C++中的string类
开发语言·c++
jz_ddk8 分钟前
[实战]调频(FM)和调幅(AM)信号生成(完整C语言实现)
c语言·算法·信号处理
Tipriest_19 分钟前
[数据结构与算法] 优先队列 | 最小堆 C++
c++·优先队列·数据结构与算法·最小堆
CloudAce云一24 分钟前
谷歌云代理商:谷歌云TPU/GPU如何加速您的AI模型训练和推理
算法
宛西南浪漫戈命32 分钟前
Centos 7下使用C++使用Rdkafka库实现生产者消费者
c++·centos·linq
轻语呢喃1 小时前
每日LeetCode : 杨辉三角
javascript·后端·算法
码农Cloudy.1 小时前
C语言<数据结构-链表>
c语言·数据结构·链表
YuTaoShao2 小时前
【LeetCode 热题 100】148. 排序链表——(解法二)分治
java·算法·leetcode·链表
Shilong Wang2 小时前
三维旋转沿轴分解
算法·计算机视觉·机器人
帅_shuai_2 小时前
C++ 模板参数展开
c++