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;
    }
};
相关推荐
慕容青峰5 分钟前
【加拿大计算机竞赛 CCO 小行星采矿】题解
c++·算法·sublime text
Ghost-Silver10 分钟前
2025年度总结
开发语言·数据结构·c++·算法
POLITE318 分钟前
Leetcode 54.螺旋矩阵 JavaScript (Day 8)
javascript·leetcode·矩阵
你撅嘴真丑19 分钟前
成绩排序 与 整数奇偶排序
数据结构
yyy(十一月限定版)24 分钟前
C++基础
java·开发语言·c++
谈笑也风生30 分钟前
经典算法题型之排序算法(四)
数据结构·算法·排序算法
AI科技星31 分钟前
空间螺旋电磁耦合常数 Z‘:拨开迷雾,让电磁力变得直观易懂
服务器·人工智能·科技·算法·生活
亚伯拉罕·黄肯44 分钟前
强化学习算法笔记
笔记·算法
only-qi1 小时前
LeetCode 148. 排序链表
算法·leetcode·链表
岁岁的O泡奶1 小时前
NSSCTF_crypto_[SWPUCTF 2023 秋季新生赛]dpdp
经验分享·python·算法·密码学