Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Find the minimum number of single-bit flips in a and b so that (a OR b) == c.

Problem: Find the minimum number of single-bit flips in a and b so that (a OR b) == c.
def flips(a, b, c):
    res = 0
    while a or b or c:
        x, y, z = a & 1, b & 1, c & 1
        if z == 0: res += x + y
        elif x == 0 and y == 0: res += 1
        a, b, c = a >> 1, b >> 1, c >> 1
    return res
print(flips(9, 12, 6))
What is printed?
  1. A. 3
  2. B. 4
  3. C. 5
  4. D. 2

Correct answer: B. 4

9 = 1001, 12 = 1100, 6 = 0110. Bit 0: c = 0 but a = 1 (1 flip). Bit 1: c = 1 but both 0 (1 flip). Bit 2: b already 1. Bit 3: c = 0 but both are 1 (2 flips). Total 4; the trap is counting only 1 for bit 3.

More Coding Interview Problems questions

Exams that ask this topic