461. Hamming Distance*(汉明距离)

本文解析了如何使用C++中的异或操作和位计数技巧解决LeetCode上的汉明距离问题。通过理解整数与操作删除最右边的1,演示了如何在Solution类中利用countBits方法计算两个整数的异或结果中1的个数,从而得到汉明距离。

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

461. Hamming Distance*(汉明距离)

https://leetcode.com/problems/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 <= 2^31 - 1

C++ 实现 1

这类和二进制位的问题, 需要记住一些结论, 这些结论在 191. Number of 1 Bits*231. Power of Two 这些题中也出现了, 即对于一个整数 n, 它和 n - 1 进行 “与” 操作(即 &), 可以将 n 的二进制表示中最右边的 1 给删除.

比如 n = 0x00001100, 那么 n & (n - 1) 的结果为 0x00001000. 这样的话, 使用

int count = 0;
while (n) {
	n &= (n - 1);
	count += 1;
} 

这段代码, 可以用于整数 n 的二进制表示中 1 的个数.

知晓上面的结论, 再来求解本题, 相当容易了, 先计算 res = x ^ y, 即两个整数的异或, 再统计 res 的二进制表示中 1 的个数即可.

class Solution {
private:
    int countBits(int n) {
        int count = 0;
        while (n) {
            count += 1;
            n &= (n - 1);
        }
        return count;
    }
public:
    int hammingDistance(int x, int y) {
        int res = x ^ y;
        return countBits(res);
    }
};

> 这里是引用

开发板推荐:天空星STM32F407VET6开发板

超高性价比 STM32主控 | 超高主频 | 一板兼容百芯 | 比赛神器 | 沉金彩色丝印

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值