题目:
The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
Given two integers x and y, calculate the Hamming distance.
Note:
0 ≤ x, y < 231.
Example:
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.
思路:
求出x,y的分别二进制表示,再求其异或,但是有个问题点需要注意:Python中如果求两个数的异或,如 x^y 则先把x,y分别转化为二进制,在求其异或值,返回的是一个十进制的整数,此时需要将十进制转化为二进制,并数一下有多少个1,则为最终不同的位。
代码:
class Solution:
def hammingDistance(self, x: int, y: int) -> int:
return(bin(x^y).count('1'))
本文介绍如何计算两个整数之间的Hamming距离,即二进制表示下不同位的数量。通过使用异或运算和位操作,文章提供了一个简洁的Python实现。
288

被折叠的 条评论
为什么被折叠?



