LeetCode 461 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
, calculate the Hamming distance.
Note:0 ≤ x
, y
< 231.
题目分析及思路
题目给出两个整数,要求返回它们之间的Hamming distance。Hamming distance指的是两个整数对应的二进制的对应位上数字不同的个数。可以先对两个整数做异或操作,然后对结果的每一位和1做与操作,若等于1就加一,否则就跳过。
python代码
class Solution:
def hammingDistance(self, x, y):
"""
:type x: int
:type y: int
:rtype: int
"""
bits = x ^ y
count = 0
for i in range(0,32):
if bits & 1 != 0:
count = count + 1
bits = bits >> 1
return count