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;
    }
};
相关推荐
杨校13 小时前
杨校老师课堂备赛C++信奥之模拟算法习题专项训练
开发语言·c++·算法
世洋Blog13 小时前
AStar算法基础学习总结
算法·面试·c#·astar·寻路
haing201914 小时前
七轴协作机器人运动学正解计算方法
算法·机器学习·机器人
谈笑也风生14 小时前
把二叉搜索树转换为累加树(一)
算法
youngee1114 小时前
hot100-64跳跃游戏
算法·游戏
hd51cc15 小时前
MFC 文档/视图 二
c++·mfc
wzfj1234515 小时前
认识lambda
c++
老王熬夜敲代码15 小时前
C++万能类:any
开发语言·c++·笔记
POLITE315 小时前
Leetcode 19. 删除链表的倒数第 N 个结点 JavaScript (Day 11)
javascript·leetcode·链表
liu****15 小时前
机器学习-线性回归
人工智能·python·算法·机器学习·回归·线性回归