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;
    }
};
相关推荐
想做小南娘,发现自己是女生喵1 小时前
第 2 章 顺序表和 vector
java·数据结构·算法
ComputerInBook1 小时前
c 和 c++ 中的宏块(macro)
c语言·c++··宏块·宏指令
艾醒2 小时前
2026年第29周(7.13-7.19)AI全复盘:技术突破、行业趣闻翻车、算力服务器商业动态
人工智能·算法
AA陈超2 小时前
004 T02 - 俯视角摄像机系统 设计文档
网络·c++·ue5·虚幻引擎
雪碧聊技术2 小时前
动态规划算法—01背包问题
算法·动态规划
bu_shuo2 小时前
c与cpp中的argc和argv
c语言·c++·算法
普贤莲花2 小时前
【2026年第29周---写于20260718】---整理,断舍离
程序人生·算法·生活
蓝创精英团队2 小时前
VCPKG 跨平台C++ 库管理器
c++·vcpkg
Reart2 小时前
Leetcode 674.最长连续递增序列 (719)
后端·算法
Reart3 小时前
Leetcode 300.最长递增子序列(719)
算法