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;
    }
};
相关推荐
plus4s25 分钟前
2月15日(78,80,81题)
c++·算法·图论
能源系统预测和优化研究38 分钟前
【原创改进代码】考虑碳交易与电网交互波动惩罚的共享储能电站优化配置与调度模型
算法·能源
9359639 分钟前
机考27 翻译21 单词14
c语言·数据结构·算法
回敲代码的猴子2 小时前
2月14日打卡
算法
blackicexs3 小时前
第四周第七天
算法
期末考复习中,蓝桥杯都没时间学了3 小时前
力扣刷题19
算法·leetcode·职场和发展
Renhao-Wan3 小时前
Java 算法实践(四):链表核心题型
java·数据结构·算法·链表
zmzb01034 小时前
C++课后习题训练记录Day104
开发语言·c++
honiiiiii4 小时前
SMU winter week4
c++
踩坑记录4 小时前
递归回溯本质
leetcode