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;
    }
};
相关推荐
米尔的可达鸭5 小时前
深入操作系统 Socket 底层:EPOLLOUT 可写事件管理 + 非阻塞异步
开发语言·网络·数据结构·经验分享·websocket·网络协议
HZZD_HZZD5 小时前
碳核查场景下能源计量数据精准采集与碳排放核算算法全链路实战:从智能电表协议适配到排放因子动态计算
算法·能源
啦啦啦啦啦zzzz5 小时前
c++web服务器框架Oat++的API应用
服务器·c++·oat++
饼干哥哥6 小时前
10.5% 深层转化、90%+ 新用户,ChatGPT Ads 值得吗?
算法·正则表达式·编程语言
Irissgwe6 小时前
算法之二分查找
数据结构·c++·算法·二分查找
zh_xuan6 小时前
c++ span的用法
开发语言·c++·span
亿牛云爬虫专家6 小时前
代理IP质量评估:如何建立一套代理IP的多维度评分与淘汰算法?
tcp/ip·算法·爬虫代理·延迟·免费代理ip·连通率·时效
zzz_23686 小时前
【Java实习面试算法冲刺】动态规划
java·算法·面试
小蒋学算法6 小时前
算法-滑动窗口最大值
数据结构·算法
t-think6 小时前
一起think C++:C++基础篇(一)—— namespace、IO、缺省参数与函数重载
c++