mirror of
https://github.com/autistic-symposium/master-algorithms-py.git
synced 2025-06-08 23:22:48 -04:00
bitwise
This commit is contained in:
parent
fa83f7e42a
commit
0d5e21b867
9 changed files with 148 additions and 2 deletions
interview_cake/bitwise_stuff
37
interview_cake/bitwise_stuff/count_bits.py
Normal file
37
interview_cake/bitwise_stuff/count_bits.py
Normal file
|
@ -0,0 +1,37 @@
|
|||
#!/usr/bin/python
|
||||
|
||||
''' This method returns the number of bits that are necessary to change to convert two
|
||||
numbers A and B:
|
||||
1) XOR
|
||||
2) count 1s
|
||||
'''
|
||||
|
||||
def count_bits_swap2(a, b):
|
||||
count = 0
|
||||
m = a^b
|
||||
while m:
|
||||
count +=1
|
||||
m = m & (m-1)
|
||||
return count
|
||||
|
||||
|
||||
|
||||
def count_bits_swap(a, b):
|
||||
m = a^b
|
||||
return count_1s(m)
|
||||
|
||||
|
||||
def count_1s(m):
|
||||
count = 0
|
||||
while m:
|
||||
if m& 1 :
|
||||
count +=1
|
||||
m >>= 1
|
||||
return count
|
||||
|
||||
|
||||
if __name__ == '__main__':
|
||||
a = int('10010000', 2)
|
||||
b = int('01011010', 2)
|
||||
print count_bits_swap(a, b) #4
|
||||
print count_bits_swap2(a, b) #4
|
Loading…
Add table
Add a link
Reference in a new issue