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;
    }
};
相关推荐
HXDGCL7 分钟前
矩形环形导轨:自动化循环线的核心运动单元解析
运维·算法·自动化
谭欣辰18 分钟前
C++ 排列组合完整指南
开发语言·c++·算法
代码中介商32 分钟前
银行管理系统的业务血肉 —— 流程、状态机、输入校验与持久化(下篇)
c语言·算法
橙子也要努力变强1 小时前
信号捕捉底层机制-机理篇2
linux·服务器·c++
foundbug9991 小时前
自适应滤除直达波干扰的MATLAB实现
开发语言·算法·matlab
盐焗鹌鹑蛋1 小时前
【C++】stack和queue类
c++
MegaDataFlowers2 小时前
206.反转链表
数据结构·链表
郝学胜-神的一滴2 小时前
罗德里格斯旋转公式(Rodrigues‘ Rotation Formula)完整推导
c++·unity·godot·图形渲染·three.js·unreal
lzh200409192 小时前
深入理解进程:从PCB内核结构到写时拷贝的底层实战
linux·c++
aseity3 小时前
跨平台项目中QString 与 非Qt 跨平台动态库在字符集上的一个实用的互操作约定.
c++·经验分享