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;
    }
};
相关推荐
爱看科技12 分钟前
微美全息(NASDAQ:WIMI)容错量子计算赋能,大规模机器学习模型高效量子算法获突破
算法·机器学习·量子计算
敲上瘾22 分钟前
Linux系统C++开发环境搭建工具(三)—— brpc使用指南
linux·c++·分布式·rpc
_dindong30 分钟前
牛客101:递归/回溯
数据结构·c++·笔记·学习·算法·leetcode·深度优先
AA陈超41 分钟前
虚幻引擎5 GAS开发俯视角RPG游戏 P06-31 映射标签到属性
c++·游戏·ue5·游戏引擎·虚幻
刃神太酷啦1 小时前
力扣校招算法通关:双指针技巧全场景拆解 —— 从数组操作到环检测的高效解题范式
java·c语言·数据结构·c++·算法·leetcode·职场和发展
西瓜树枝1 小时前
遗传算法与属性约简:原理、代码与参数配置
算法
haofafa1 小时前
STL之动态数组
开发语言·c++
jerryinwuhan1 小时前
理论及算法_时间抽取论文
前端·算法·easyui
小蒋学算法2 小时前
贪心算法:IPO
算法
得物技术2 小时前
大模型如何革新搜索相关性?智能升级让搜索更“懂你”|得物技术
算法·搜索引擎·排序算法