Data Structures & AlgorithmsHardAmazon · Microsoft OA

Problem: Divide two integers without , / or %, truncating toward zero, using doubling (shifts).

Problem: Divide two integers without *, / or %, truncating toward zero, using doubling (shifts).
def divide(a, b):
    neg = (a < 0) != (b < 0); a, b = abs(a), abs(b); q = 0
    while a >= b:
        t, m = b, 1
        while a >= t << 1: t <<= 1; m <<= 1
        a -= t; q += m
    return -q if neg else q
print(divide(100, 7), divide(-23, 4))
What is printed?
  1. A. 14 -5
  2. B. 14 -6
  3. C. 15 -5
  4. D. 13 -5

Correct answer: A. 14 -5

100 = 7·8 + 44 → 44 = 7·4 + 16 → 16 = 7·2 + 2, so q = 8 + 4 + 2 = 14. −23 / 4 = −5.75 truncates toward zero to −5 (Python's // would floor to −6).

More Coding Interview Problems questions

Exams that ask this topic