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;
    }
};
相关推荐
故事和你915 分钟前
sdut-python-实验四-python序列结构(21-27)
大数据·开发语言·数据结构·python·算法
memcpy09 分钟前
LeetCode 1456. 定长子串中元音的最大数目【定长滑窗模板题】中等
算法·leetcode·职场和发展
liuyao_xianhui13 分钟前
优选算法_模拟_提莫攻击_C++
开发语言·c++·算法·动态规划·哈希算法·散列表
丶小鱼丶26 分钟前
数据结构和算法之【栈】
java·数据结构
玛丽莲茼蒿28 分钟前
LeetCode hot100【相交链表】【简单】
算法·leetcode·职场和发展
罗湖老棍子28 分钟前
They Are Everywhere(Codeforces- P701C)
算法·滑动窗口·codeforce题解
wen__xvn28 分钟前
力扣模拟题刷题
算法·leetcode
bbbb36528 分钟前
算法复杂度与能耗关系的多变量分析研究的技术7
算法
不要秃头的小孩31 分钟前
力扣刷题——111.二叉树的最小深度
数据结构·python·算法·leetcode
.select.32 分钟前
c++ 移动赋值/移动构造函数
开发语言·c++