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;
    }
};
相关推荐
一拳一个呆瓜1 小时前
【STL】iostream 编程:检测提取操作产生的错误
c++·stl
稚南城才子,乌衣巷风流1 小时前
判断素数与拓展应用
c++
众少成多积小致巨1 小时前
C++ 规范参考(下)
c++
c238561 小时前
把 C++ 内存分配拆透:new 与 malloc 的三层血缘
开发语言·c++·算法
aaaameliaaa2 小时前
指针之总结
c语言·笔记·算法
宵时待雨2 小时前
优选算法专题9:哈希表
数据结构·算法·散列表
txzrxz2 小时前
最短路问题——Dijkstra 算法
数据结构·c++·算法·最短路·优先队列
gwf2162 小时前
磨损均衡算法(Wear Leveling)——SSD如何让每块闪存“公平退休“?
运维·数据库·人工智能·python·嵌入式硬件·算法·智能硬件
noipp3 小时前
推荐题目:洛谷 P6231 [JSOI2013] 公交系统
c语言·数据结构·c++·算法·游戏·洛谷·luogu
c238563 小时前
C/C++每日一练6
c语言·c++·算法