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;
    }
};
相关推荐
plus4s14 分钟前
2月12日(70-72题)
算法
m0_6727033121 分钟前
上机练习第24天
算法
Mr_WangAndy24 分钟前
C++数据结构与算法_线性表_数组_概念动态数组,刷题
c++·二分查找·数组刷题·数组字符串逆序·零移动·有序数组的平方
阿猿收手吧!27 分钟前
【C++】jthread:优雅终止线程新方案
开发语言·c++
edisao1 小时前
序幕-内部审计备忘录
java·jvm·算法
十五年专注C++开发1 小时前
C++中各平台表示Debug的宏
开发语言·c++·debug
shehuiyuelaiyuehao1 小时前
22Java对象的比较
java·python·算法
Dev7z2 小时前
滚压表面强化过程中变形诱导位错演化与梯度晶粒细化机理的数值模拟研究
人工智能·python·算法
吴秋霖2 小时前
apple游客下单逆向分析
python·算法·逆向分析
阿猿收手吧!3 小时前
【C++】Ranges:彻底改变STL编程方式
开发语言·c++