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;
    }
};
相关推荐
明朝百晓生6 分钟前
强化学习[chapter8] [page17] Value Function Methods
人工智能·算法
POLITE318 分钟前
Leetcode 56.合并区间 JavaScript (Day 6)
算法·leetcode·职场和发展
历程里程碑34 分钟前
滑动窗口秒解LeetCode字母异位词
java·c语言·开发语言·数据结构·c++·算法·leetcode
Tandy12356_44 分钟前
手写TCP/IP协议栈——TCP结构定义与基本接口实现
c语言·网络·c++·网络协议·tcp/ip·计算机网络
ghie90901 小时前
使用直接节点积分法进行无网格法2D悬臂梁计算
算法
Helibo441 小时前
2025年12月gesp3级题解
数据结构·c++·算法
p&f°1 小时前
垃圾回收两种算法
java·jvm·算法
靠沿1 小时前
Java数据结构初阶——堆与PriorityQueue
java·开发语言·数据结构
点云SLAM1 小时前
点云配准算法之- GICP算法点云配准概率模型推导和最大似然求解(MLE)
算法·机器人·slam·点云配准·最大似然估计·点云数据处理·gicp算法
禾叙_1 小时前
HashMap
java·数据结构·哈希算法