This commit is contained in:
Mia von Steinkirch 2019-05-12 18:00:11 -07:00
parent fa83f7e42a
commit 0d5e21b867
9 changed files with 148 additions and 2 deletions
interview_cake/bitwise_stuff

View 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