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;
    }
};
相关推荐
“αβ”11 分钟前
TCP相关实验
运维·服务器·网络·c++·网络协议·tcp/ip·udp
梭七y15 分钟前
【力扣hot100题】(151)课程表
算法·leetcode·哈希算法
孞㐑¥39 分钟前
算法—滑动窗口
开发语言·c++·经验分享·笔记·算法
历程里程碑43 分钟前
Linux 3 指令(3):进阶指令:文件查看、资源管理、搜索打包压缩详解
linux·运维·服务器·c语言·数据结构·笔记·算法
咋吃都不胖lyh1 小时前
GBDT 中的前向分布算法和贪婪学习
学习·算法
leo__5201 小时前
CLEAN算法仿真程序,用于雷达信号中的杂波抑制
算法
一分之二~1 小时前
二叉树--求最小深度(迭代和递归)
数据结构·c++·算法·leetcode·深度优先
老鼠只爱大米1 小时前
LeetCode经典算法面试题 #24:两两交换链表中的节点(迭代法、递归法等多种实现方案详细解析)
算法·leetcode·链表·递归·双指针·迭代·链表交换
mjhcsp1 小时前
挑战训练一个 AlphaZero 五子棋
算法·洛谷
Word码1 小时前
leetcode260.只出现一次的数字III
算法