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;
    }
};
相关推荐
D_evil__15 分钟前
【Effective Modern C++】第三章 转向现代C++:15. 尽可能使用constexpr
c++
2301_8213696125 分钟前
嵌入式实时C++编程
开发语言·c++·算法
sjjhd65227 分钟前
多核并行计算优化
开发语言·c++·算法
weixin_3954489142 分钟前
main.c_cursor_0130
前端·网络·算法
田野追逐星光1 小时前
STL的容器vector的模拟实现
开发语言·c++
半壶清水1 小时前
[软考网规考点笔记]-操作系统核心知识及历年真题解析
网络·网络协议·算法
Tansmjs2 小时前
实时数据可视化库
开发语言·c++·算法
WBluuue2 小时前
Codeforces 1075 Div2(ABC1C2D1D2)
c++·算法
圣保罗的大教堂2 小时前
leetcode 3650. 边反转的最小路径总成本 中等
leetcode
添砖java‘’2 小时前
线程的互斥与同步
linux·c++·操作系统·线程·信息与通信