Data Structures & AlgorithmsVery hardProduct company OA

Problem: Write an integer in base −2 (digits 0/1, place values 1, −2, 4, −8, …). When Python's divmod by −2 gives a negative remainder, fix it to a positive digit.

Problem: Write an integer in base −2 (digits 0/1, place values 1, −2, 4, −8, …). When Python's divmod by −2 gives a negative remainder, fix it to a positive digit.
def neg2(n):
    if n == 0: return "0"
    d = []
    while n:
        n, r = divmod(n, -2)
        if r < 0: n, r = n + 1, r + 2
        d.append(str(r))
    return "".join(reversed(d))
print(neg2(6), neg2(-3), neg2(13))
What is printed?
  1. A. 110 1101 11101
  2. B. 11010 111 11101
  3. C. 11010 1101 1101
  4. D. 11010 1101 11101

Correct answer: D. 11010 1101 11101

Check by place values (from the right) 1, −2, 4, −8, 16: 11010 = 16 − 8 − 2 = 6; 1101 = −8 + 4 + 1 = −3; 11101 = 16 − 8 + 4 + 1 = 13. Python's divmod floors, so with a negative divisor the remainder is 0 or −1; the fix-up (r + 2, n + 1) keeps digits in {0, 1}. The plain binary of 6 (110) is wrong in base −2. O(log |n|).

More Coding Interview Problems questions

Exams that ask this topic