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;
    }
};
相关推荐
Rain的Java大神之路13 分钟前
LeetCode 46 全排列:从「及格答案」到让面试官眼前一亮的三种写法
后端·leetcode·面试
不知棋者20 分钟前
C++ 排序算法大全
开发语言·c++·排序算法
程序员与背包客_CoderZ25 分钟前
Linux C++异步网络编程:c-ares高性能DNS解析编码实战
linux·服务器·c语言·开发语言·网络·c++·网络编程
idealzouhu30 分钟前
CMake 核心概念与实战指南
c++·c·cmake
LabVIEW开发39 分钟前
探测器脉冲只有 500 ns,谱线要分 2048 道:LabVIEW 怎么把振动台和计数器锁在同一根时间轴上
人工智能·算法·labview
小O的算法实验室1 小时前
SEVC,面向拥塞感知的无人机-卡车协同路径规划的深度强化学习框架
算法
小则又沐风a1 小时前
线程的互斥和同步
linux·c++
醉颜凉1 小时前
区块链不可篡改机制全解析:从哈希锁链到51%攻击
算法·区块链·哈希算法
我是伪码农1 小时前
12.5程序设计
数据结构·算法