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;
    }
};
相关推荐
一颗青果8 分钟前
auto | 尾置返回类型 | decltype | using | typedef
java·开发语言·算法
郝学胜-神的一滴15 分钟前
何友院士《人工智能发展前沿》全景解读:从理论基石到产业变革
人工智能·python·深度学习·算法·机器学习
BHXDML25 分钟前
第五章:支持向量机
算法·机器学习·支持向量机
2401_8414956429 分钟前
具身智能:从理论到现实,人工智能的下一场革命
人工智能·算法·机器人·硬件·具身智能·通用智能·专用智能
Felven35 分钟前
B. MEXor Mixup
算法
阿崽meitoufa1 小时前
JVM虚拟机:垃圾收集算法
java·jvm·算法
练习时长一年1 小时前
LeetCode热题100(分割等和子集)
算法·leetcode·职场和发展
Frank_refuel1 小时前
C++之继承
开发语言·c++
52Hz1181 小时前
力扣148.排序链表
leetcode
七号驿栈1 小时前
07_汽车信息安全算法在线验证工具(测试报告)
算法