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;
    }
};
相关推荐
学Linux的语莫19 分钟前
机器学习数据处理
java·算法·机器学习
逆小舟1 小时前
【C/C++】指针
c语言·c++·笔记·学习
earthzhang20211 小时前
【1007】计算(a+b)×c的值
c语言·开发语言·数据结构·算法·青少年编程
江公望1 小时前
Qt QtConcurrent使用入门浅解
c++·qt·qml
我是华为OD~HR~栗栗呀1 小时前
23届考研-Java面经(华为OD)
java·c++·python·华为od·华为·面试
爱吃喵的鲤鱼1 小时前
仿mudou——Connection模块(连接管理)
linux·运维·服务器·开发语言·网络·c++
郝学胜-神的一滴2 小时前
使用Linux的read和write系统函数操作文件
linux·服务器·开发语言·数据库·c++·程序人生·软件工程
2301_803554522 小时前
C++联合体(Union)详解:与结构体的区别、联系与深度解析
java·c++·算法
pu_taoc2 小时前
深入剖析:基于epoll与主从Reactor模型的高性能服务器设计与实现
服务器·c语言·c++·vscode
初圣魔门首席弟子3 小时前
c++ bug 函数定义和声明不一致导致出bug
开发语言·c++·bug