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?- A. 110 1101 11101
- B. 11010 111 11101
- C. 11010 1101 1101
- 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
- Problem: Convert a fraction to a decimal string, putting a repeating part in parentheses: remember at which output position each remainder…
- Problem: Fibonacci numbers modulo m repeat with the Pisano period π(m). Use it to get F(10¹⁸) mod 10 without big loops. python def…
- Problem: Compute 3^(5^20) mod p for the prime p = 10⁹ + 7. By Fermat, exponents can be reduced modulo p − 1 (since gcd(3, p) = 1). Which…
- Problem: Two equal-length strings over {x, y}; one move swaps s1[i] with s2[j] (any i, j). Minimum moves to make them equal (−1 if…
- Problem: Rabin–Karp search with a rolling hash: (a) base 10, modulus 7; (b) base 256, modulus 1000003. Count true matches and spurious…
- Problem: A primality helper tries divisors while i·i ≤ n. How many loop iterations run for n = 10⁶ and for n = 99, and what is the…