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;
    }
};
相关推荐
万能程序员-传康Kk2 小时前
旅游推荐数据分析可视化系统算法
算法·数据分析·旅游
PXM的算法星球2 小时前
【并发编程基石】CAS无锁算法详解:原理、实现与应用场景
算法
ll7788112 小时前
C++学习之路,从0到精通的征途:继承
开发语言·数据结构·c++·学习·算法
烨然若神人~2 小时前
算法第十七天|654. 最大二叉树、617.合并二叉树、700.二叉搜索树中的搜索、98.验证二叉搜索树
算法
爱coding的橙子2 小时前
每日算法刷题Day2 5.10:leetcode数组1道题3种解法,用时40min
算法·leetcode
我不想当小卡拉米2 小时前
【Linux】操作系统入门:冯诺依曼体系结构
linux·开发语言·网络·c++
Akiiiira2 小时前
【数据结构】栈
数据结构
炎芯随笔2 小时前
【C++】【设计模式】生产者-消费者模型
开发语言·c++·设计模式
阳洞洞2 小时前
leetcode 18. 四数之和
leetcode·双指针
乌鸦9443 小时前
《类和对象(下)》
开发语言·c++·类和对象+