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;
    }
};
相关推荐
草莓熊Lotso28 分钟前
Linux 实战:从零实现动态进度条(含缓冲区原理与多版本优化)
linux·运维·服务器·c++·人工智能·centos·进度条
行稳方能走远1 小时前
Android C++ 学习笔记3
android·c++
练习时长一年1 小时前
Leetcode热题100(跳跃游戏 II)
算法·leetcode·游戏
小白菜又菜7 小时前
Leetcode 3432. Count Partitions with Even Sum Difference
算法·leetcode
wuhen_n8 小时前
LeetCode -- 15. 三数之和(中等)
前端·javascript·算法·leetcode
sin_hielo8 小时前
leetcode 2483
数据结构·算法·leetcode
Xの哲學9 小时前
Linux多级时间轮:高精度定时器的艺术与科学
linux·服务器·网络·算法·边缘计算
大头流矢9 小时前
归并排序与计数排序详解
数据结构·算法·排序算法
阿闽ooo9 小时前
外观模式:从家庭电源控制看“简化接口“的设计智慧
c++·设计模式·外观模式
油泼辣子多加9 小时前
【信创】算法开发适配
人工智能·深度学习·算法·机器学习