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;
    }
};
相关推荐
深邃-几秒前
数据结构-双向链表
c语言·开发语言·数据结构·c++·算法·链表·html5
2401_878530212 分钟前
分布式任务调度系统
开发语言·c++·算法
艾莉丝努力练剑8 分钟前
【Linux:文件】文件基础IO进阶
linux·运维·服务器·c语言·网络·c++·centos
_深海凉_19 分钟前
LeetCode热题100-两数之和
算法·leetcode·职场和发展
程序猿编码19 分钟前
基于ncurses的TCP连接可视化与重置工具:原理与实现(C/C++代码实现)
linux·c语言·网络·c++·tcp/ip
nunca_te_rindas23 分钟前
算法刷体小结汇总(C/C++)20260328
c语言·c++·算法
Sunshine for you25 分钟前
高性能压缩库实现
开发语言·c++·算法
Sunshine for you26 分钟前
C++中的表达式模板
开发语言·c++·算法
qwehjk200827 分钟前
C++中的状态模式
开发语言·c++·算法
白藏y28 分钟前
【C++】cpp-httplib基础使用
c++·cpp-httplib