File tree 1 file changed +11
-7
lines changed 1 file changed +11
-7
lines changed Original file line number Diff line number Diff line change 1
-
2
1
def hamming_distance (x , y ):
3
2
difference = x ^ y
4
3
count = 0
5
- while difference != 0 :
6
- count += 1
4
+ while difference :
7
5
# this removes ones from right to left (least to most significant)
8
6
difference &= difference - 1
7
+ count += 1
9
8
return count
10
9
11
10
12
- # Kernighan method
11
+ # Wegner method
13
12
def hamming_weight (x ):
13
+ if x < 0 :
14
+ return None
15
+
14
16
count = 0
15
- while x != 0 :
16
- count += 1
17
+ while x :
17
18
x &= x - 1
19
+ count += 1
20
+
18
21
return count
19
22
20
23
21
24
def pop_count (i ):
22
- i = i - ((i >> 1 ) & 0x55555555 )
25
+ i -= ((i >> 1 ) & 0x55555555 )
23
26
i = (i & 0x33333333 ) + ((i >> 2 ) & 0x33333333 )
24
27
return (((i + (i >> 4 ) & 0xF0F0F0F ) * 0x1010101 ) & 0xffffffff ) >> 24
25
28
@@ -205,5 +208,6 @@ def main():
205
208
print ("swap 213, 14" , swap_ints (213 , 14 ))
206
209
print ("swap 872, 992" , swap_ints (872 , 992 ))
207
210
211
+
208
212
if __name__ == "__main__" :
209
213
main ()
You can’t perform that action at this time.
0 commit comments