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;
    }
};
相关推荐
leaves falling1 分钟前
c语言-给定两个数,求这两个数的最大公约数
数据结构·算法
SamtecChina20231 分钟前
Electronica现场演示 | 严苛环境下的56G互连
大数据·网络·人工智能·算法·计算机外设
想做后端的小C2 分钟前
数据结构:线性表原地逆置
数据结构·考研
Tim_102 分钟前
【C++入门】05、复合类型-数组
开发语言·c++·算法
jikiecui2 分钟前
信奥崔老师:三目运算 (Ternary Operator)
数据结构·c++·算法
无限进步_3 分钟前
【C语言&数据结构】另一棵树的子树:递归思维的双重奏
c语言·开发语言·数据结构·c++·算法·github·visual studio
t198751283 分钟前
同伦(Homotopy)算法求解非线性方程组
算法
圣保罗的大教堂3 分钟前
leetcode 1266. 访问所有点的最小时间 简单
leetcode
汉克老师3 分钟前
GESP2025年9月认证C++一级真题与解析(判断题1-10)
c++·数据类型·累加器·循环结构·gesp一级·gesp1级
Elwin Wong9 分钟前
从 Louvain 到 Leiden:保证社区连通性的社区检测算法研究解读
算法·社区检测·graphrag·louvain·leiden