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;
    }
};
相关推荐
夏幻灵21 分钟前
每日一题:LeetCode 165:比较版本号
算法·leetcode·职场和发展
道尔柯南22 分钟前
C++ 面向对象编程入门:类和对象(上)
开发语言·c++·算法
Navigator_Z36 分钟前
LeetCode //C - 1288. Remove Covered Intervals
c语言·算法·leetcode
码爸1 小时前
决策树介绍与示例
python·算法·机器学习
动词ing1 小时前
【题目练习】字符串相乘
算法
0+1112 小时前
算法 --链表
数据结构·算法·leetcode·链表
圣保罗的大教堂2 小时前
leetcode 2333. 最小差值平方和 中等
leetcode
aqiu1111112 小时前
【C++算法打怪专栏】C++ `unordered_set` 常用初始化与插入方法总结
开发语言·c++·算法
Terra.K2 小时前
高精度阶乘求和模板深度解析
开发语言·c++·算法
智码看视界2 小时前
C++智能指针全景剖析及面试20问
开发语言·c++·深度学习·面试·内存管理·智能指针