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;
    }
};
相关推荐
宝贝儿好16 小时前
【强化学习实战】第十一章:Gymnasium库的介绍和使用(1)、出租车游戏代码详解(Sarsa & Q learning)
人工智能·python·深度学习·算法·游戏·机器学习
2401_8846022719 小时前
程序人生-Hello’s P2P
c语言·c++
weixin_4588726119 小时前
东华复试OJ二刷复盘2
算法
Charlie_lll19 小时前
力扣解题-637. 二叉树的层平均值
算法·leetcode
初中就开始混世的大魔王19 小时前
2 Fast DDS Library概述
c++·中间件·信息与通信
爱淋雨的男人20 小时前
自动驾驶感知相关算法
人工智能·算法·自动驾驶
wen__xvn20 小时前
模拟题刷题3
java·数据结构·算法
滴滴答滴答答20 小时前
机考刷题之 6 LeetCode 169 多数元素
算法·leetcode·职场和发展
圣保罗的大教堂20 小时前
leetcode 1980. 找出不同的二进制字符串 中等
leetcode
娇娇yyyyyy20 小时前
C++基础(6):extern解决重定义问题
c++