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;
    }
};
相关推荐
张二娃同学4 小时前
03_变量常量与输入输出_printf与scanf详解
算法
信竞星球_少儿编程题库4 小时前
2026年全国信息素养大赛算法应用主题赛 丝路新城 C++ 模拟卷(三)
开发语言·c++
Zhang~Ling4 小时前
深入解析C++list:从0到1实现一个完整的链表类
c++·链表·list
江南十四行5 小时前
并发编程(一)
java·jvm·算法
浩浩测试一下5 小时前
汇编 位运算 (逆向分析)
汇编·逆向·位运算·asm·windows编程·二进制逆向
z200509305 小时前
今日算法(依旧二叉树)
算法·leetcode·职场和发展
Zxc_5 小时前
《遗传算法:从自然选择到Rastrigin函数优化,手写一个完整的进化求解器》
算法
王老师青少年编程5 小时前
csp信奥赛C++高频考点专项训练之字符串 --【字符串综合】:[NOIP 2015 提高组] 子串
c++·字符串·csp·高频考点·子串·信奥赛
阿Y加油吧5 小时前
两道经典动态规划题:乘积最大子数组 & 分割等和子集 复盘笔记
笔记·算法·动态规划
June`5 小时前
redis项目之命令解析器
数据库·c++·redis