ProgrammingHardGATE CS · Product-company placement

What is printed?

What is printed?
def f(n):
    out = []
    while n:
        n, r = divmod(n, -2)
        if r < 0:
            n, r = n + 1, r + 2
        out.append(str(r))
    return "".join(reversed(out)) or "0"
print(f(6), f(-3), f(0))
  1. A. 11010 1101 0
  2. B. 110 1101 0
  3. C. 11010 11 0
  4. D. 11010 1101

Correct answer: A. 11010 1101 0

This converts to base -2, fixing negative remainders. 6 = 16 - 8 - 4 + 2 = 11010 and -3 = -8 + 4 + 1 = 1101 in negabinary. For 0 the loop never runs and the `or` supplies '0'.

More Python Programming questions

Exams that ask this topic