461. Hamming Distance*(汉明距离)

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);
    }
};

> 这里是引用

猜你喜欢

转载自blog.csdn.net/Eric_1993/article/details/116033104