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 分钟前
数据结构与算法|第二十四章:算法思维总结与实战
算法·代理模式
旺仔老馒头.7 分钟前
【C++】类和对象(二)
开发语言·c++·后端·类和对象
炽烈小老头12 分钟前
【每天学习一点算法 2026/05/11】排序链表
学习·算法·链表
wefg117 分钟前
一些零散的算法
c++·算法
khalil102020 分钟前
代码随想录算法训练营Day-48 单调栈02 | 42. 接雨水、84.柱状图中最大的矩形
数据结构·c++·算法·leetcode·单调栈·接雨水
Hcoco_me20 分钟前
Ai:Agent/ infra / 智驾 / 推广算法 题库
人工智能·深度学习·算法·自动驾驶·剪枝
项目申报小狂人20 分钟前
提出了一种带双向搜索的粒子群优化算法,一种基于双四元数运动优化的新型无人机3D路径规划方法及应用
算法·3d·无人机
驼同学.20 分钟前
牛客网面试TOP101 - Python算法学习指南
python·算法·面试
大大杰哥25 分钟前
Java集合框架(List/Set/Queue)核心总结与代码示例
java·数据结构
大大杰哥31 分钟前
leetcode hot100(3)子串
c++·算法·leetcode