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;
    }
};
相关推荐
s09071365 分钟前
【综述】前视二维多波束成像声呐(FLS)图像处理算法全解析:从成像到深度学习
图像处理·人工智能·算法·声呐·前视多波束
星河耀银海13 分钟前
人工智能从入门到精通:机器学习基础算法实战与应用
人工智能·算法·机器学习
nice_lcj52024 分钟前
数据结构之堆:从概念到应用全解析(附TOP-K经典问题)
java·数据结构·算法
无言(* ̄(エ) ̄)28 分钟前
进程---Linux/C语言
java·开发语言·算法
漫随流水31 分钟前
leetcode算法(429.N叉树的层序遍历)
数据结构·算法·leetcode·二叉树
漫随流水34 分钟前
leetcode算法(116.填充每个节点的下一个右侧节点指针)
数据结构·算法·leetcode·二叉树
_OP_CHEN44 分钟前
【算法基础篇】(四十四)数论之欧拉定理与扩展欧拉定理深度解析:从降幂到超大规模幂运算
c++·算法·蓝桥杯·算法竞赛·欧拉定理·扩展欧拉定理·acm/icpc
lfwh1 小时前
Java 中基于 DBSCAN 算法的车辆交汇点计算实现详解
java·开发语言·算法
liulilittle1 小时前
DeepWiki: OPENPPP2 工程价值
网络·c++·网络协议·ai·信息与通信·通信
数据大魔方1 小时前
【期货量化入门】期权交易入门:从零开始学期权量化(TqSdk完整教程)
数据库·python·mysql·算法·区块链·程序员创富