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;
    }
};
相关推荐
羊小猪~~9 分钟前
【QT】-- QT基础类
开发语言·c++·后端·stm32·单片机·qt
leaves falling20 分钟前
冒泡排序(基础版+通用版)
数据结构·算法·排序算法
老鼠只爱大米25 分钟前
LeetCode算法题详解 56:合并区间
leetcode·并查集·合并区间·区间合并·线性扫描·算法面试
C雨后彩虹43 分钟前
无向图染色
java·数据结构·算法·华为·面试
坚持就完事了1 小时前
扫描线算法
算法
努力写代码的熊大1 小时前
深入探索C++关联容器:Set、Map、Multiset与Multimap的终极指南及底层实现剖析
开发语言·c++
鱼跃鹰飞1 小时前
Leetcode尊享面试100题:252. 会议室
算法·leetcode·面试
程序员-King.1 小时前
二分查找——算法总结与教学指南
数据结构·算法
Zevalin爱灰灰1 小时前
现代控制理论——第三章 线性控制系统的能控性和能观性
线性代数·算法·现代控制
kklovecode1 小时前
C语言之头文件,宏和条件编译
c语言·开发语言·算法