链接:
https://leetcode.com/problems/hamming-distance/description/
题目:
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.
思路:
^
:一种位逻辑运算符
^ —–按位异或(Xor)是一种可逆运算符,只有在两个比较的位不同时其结果是1,否则结果为0。因此在计算时应先将数值转为二进制,进行位比较,然后把所得的结果转换为原来的进制数。
Answer:
class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
# print(x^y)
return bin(x^y).count('1')