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;
    }
};
相关推荐
stsdddd1 小时前
YOLO算法建筑工地安全帽目标检测数据集16881张:标注核对笔记
算法·yolo·目标检测
CV爱数码2 小时前
论文精读|Learned Primal-Dual:把原始–对偶算法展开成网络
图像处理·算法·计算机视觉·ct·重建·断层扫描
yuniko-n2 小时前
【算法】约瑟夫环问题
java·算法
郝亚军2 小时前
manifest 中 `sha256` 与 `signValue` 的作用
java·开发语言·数据结构
syagain_zsx2 小时前
jsoncpp 使用指南:编译链接、Json::Value 取值与高频坑
c++·json·库·http格式
l1t3 小时前
测试DuckDB v2.1.0-alpha49002的bignum乘法
数据库·sql·算法·duckdb
Nil2083 小时前
LeetCode 283移动零
数据结构·算法·leetcode
CQU_JIAKE3 小时前
10.18【A】
算法
LMT流氓兔3 小时前
第五单元——第4课:给工具参数加校验
java·前端·算法·ai·langchain
布莱克6053 小时前
理解 = delete 与 = default:两种赋值语义的差异
c++