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;
    }
};
相关推荐
2301_80089510几秒前
求最小生成树kruskal还是prim--备战蓝桥杯版h
算法
代码改善世界1 分钟前
【C++ 初阶】命名空间 / 输入输出 / 缺省参数 / 函数重载
开发语言·c++
小小怪7504 分钟前
高性能密码学库
开发语言·c++·算法
Book思议-5 分钟前
【数据结构实战】 C 语言单链表通关:初始化 / 头插 / 尾插 / 增删改查全实现(附图解、可运行完整代码)
c语言·数据结构·算法
2301_821700537 分钟前
模板代码生成工具
开发语言·c++·算法
佳木逢钺9 分钟前
机器人/无人机视觉开发选型指南:RealSense D455 vs D435i 与奥比中光的互补方案
c++·人工智能·计算机视觉·机器人·ros·无人机
wuhen_n10 分钟前
回溯算法入门 - LeetCode经典回溯算法题
前端·javascript·算法
宵时待雨13 分钟前
C++笔记归纳12:二叉搜索树
开发语言·数据结构·c++·笔记·算法
炎爆的土豆翔14 分钟前
SIMD常见操作,结合样例一文理解
开发语言·c++·算法
仰泳的熊猫20 分钟前
题目2305:蓝桥杯2019年第十届省赛真题-等差数列
数据结构·c++·算法·蓝桥杯