题目:
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'))