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;
    }
};
相关推荐
蚊子码农2 小时前
算法题解记录--239滑动窗口最大值
数据结构·算法
liliangcsdn3 小时前
A3C算法从目标函数到梯度策略的探索
算法
陈天伟教授3 小时前
人工智能应用- 材料微观:06.GAN 三维重构
人工智能·神经网络·算法·机器学习·重构·推荐算法
liliangcsdn4 小时前
A3C强化学习算法的探索和学习
算法
Figo_Cheung4 小时前
Figo《量子几何学:从希尔伯特空间到全息时空的统一理论体系》(二)
算法·机器学习·几何学·量子计算
额,不知道写啥。4 小时前
HAO的线段树(中(上))
数据结构·c++·算法
LYS_06184 小时前
C++学习(5)(函数 指针 引用)
java·c++·算法
紫陌涵光5 小时前
669. 修剪二叉搜索树
算法·leetcode
NGC_66115 小时前
二分查找算法
java·javascript·算法