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;
    }
};
相关推荐
非优秀程序员3 小时前
第05章 播放器大战,暴风、快播与那一夜|《互联网产品恩仇录》
算法
文丑颜不良啊6 小时前
LeetCode2481~2500题目解析
java·leetcode
武子康10 小时前
驾驶轨迹换个坐标,就能给移动机器人用吗?
人工智能·算法·机器学习
David猪大卫10 小时前
【C++修炼】map 和 set 的使用
c语言·开发语言·数据结构·c++·经验分享·笔记·学习
HPtiger10 小时前
C++ 入门笔记:从 C 到 C++ 的核心过渡(命名空间、输入输出、缺省参数、重载、引用、内联)
c语言·c++·学习
vvilkim12 小时前
数据结构类型、区别与应用场景:一篇讲透选型逻辑
数据结构
文丑颜不良啊13 小时前
LeetCode2461~2480题目解析
java·leetcode
努力努力再努力wz13 小时前
【Lua 进阶系列】从 C++ 对象到 Lua 变量:一文理解 userdata、Lua 栈与元表绑定机制
c++·junit·lua
慧都产品智能化14 小时前
Qt 表格升级攻略:复用已有编辑器,减少重复开发
c++·qt·编辑器·qt6.3