interview-preparation / what-we-do

0 stars 8 forks source link

[Bit Manipulation] interview questions #6 #80

Closed rygh4775 closed 5 years ago

rygh4775 commented 5 years ago

Conversion: Write a function to determine the number of bits you would need to flip to convert integer A to integer B.

btakeya commented 5 years ago

to make A into B by flipping bits, flip different bits between A and B.

  1. different bits between A and B: A ^ B (XOR)
  2. count how many 1 bits in result of 1.
    # simple method: shift and count
    def count1s_1(num):
    count = 0
    while num > 0:
     if num % 2 == 1:
       count += 1
     num >>= 1
    return count
    # flip 1s
    def count1s_2(num):
    count = 0
    while num != 0:
     count += 1
     num &= (num - 1)
    return count