- 汉明距离:两个数字对应二进制位不同的位置的数目。例如:x = 1, y = 4,x->2=(0,0,0,1),y->2=(0,1,0,0),汉明距离为2
- 解题思路:
- 求两个整数的异或,d=x^y,得到了一个十进制的整数;
- 然后求十进制数转为二进制后有多少个1(通过d&(d-1)可以消除1个1)
-
class Solution(object): def hammingDistance(self, x, y): """ :type x: int :type y: int :rtype: int """ #先求异或,得到十进制数 d=x^y #然后求十进制数的二进制数中有多少1 count=0 while d!=0: count+=1 d=d&(d-1) return count 作者:LeetCode-Solution 链接:https://leetcode-cn.com/problems/power-of-four/solution/4de-mi-by-leetcode-solution-b3ya/ 来源:力扣(LeetCode)