This notebook was prepared by Donne Martin. Source and license info is on GitHub.
We can use the xor operator to determine the bit differences between a and b
Complexity:
class Bits(object):
def bits_to_flip(self, a, b):
if a is None or b is None:
raise TypeError('a or b cannot be None')
count = 0
c = a ^ b
while c:
count += c & 1
c >>= 1
return count
%%writefile test_bits_to_flip.py
import unittest
class TestBits(unittest.TestCase):
def test_bits_to_flip(self):
bits = Bits()
a = int('11101', base=2)
b = int('01111', base=2)
expected = 2
self.assertEqual(bits.bits_to_flip(a, b), expected)
print('Success: test_bits_to_flip')
def main():
test = TestBits()
test.test_bits_to_flip()
if __name__ == '__main__':
main()
Overwriting test_bits_to_flip.py
%run -i test_bits_to_flip.py
Success: test_bits_to_flip