File tree 1 file changed +31
-0
lines changed
1 file changed +31
-0
lines changed Original file line number Diff line number Diff line change
1
+ # encoding:utf-8
2
+ #
3
+ # Algorithm function:
4
+ # The Hamming distance between two integers is the number of positions at which the corresponding bits are different.
5
+ # Input:
6
+ # x = 1, y = 4
7
+ # Output:
8
+ # 2
9
+ #
10
+ class Solution :
11
+ def hammingDistance (self , x , y ):
12
+ xor = x ^ y #按位异或运算符:当两对应的二进位相异时,结果为1
13
+ count = 0
14
+ while xor > 0 : #当且仅当x与y所对应的二进制的数值存在异位时,才做如下判断。
15
+ if xor & 1 : #结果为非零时成立
16
+ count += 1
17
+ xor = xor >> 1 #右移动运算符(即对其二进制的数据每次更新时去掉右数第一个元素)
18
+ return count
19
+
20
+ if __name__ == "__main__" :
21
+ a = Solution ().hammingDistance (4 ,10 )
22
+ print (a )
23
+
24
+ #算法思路
25
+ #首先通过位异或符(^)计算出两个整数的差异xor;
26
+ #其次通过将差异xor与整数1做位与运算符(&),即:当其结果为非0时,差异项数(count)加一。
27
+ #之后,通过右移动运算符(>>)将xor按位依次与整数1做比较,直至xor小于0时,循环结束。
28
+
29
+ #小结:其实整个算法最关键的是:通过位异或符(^)计算出两者差异xor后如何确定差异个数?
30
+
31
+ #关于Hamming Distance的介绍:https://en.wikipedia.org/wiki/Hamming_distance
You can’t perform that action at this time.
0 commit comments