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?- A. 14 -5
- B. 14 -6
- C. 15 -5
- 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
- Problem: Traverse a matrix along anti-diagonals, alternating direction (up-right first). python def diag(m): R, C = len(m), len(m[0]); out…
- Edge case: building a 3 × 3 grid with list multiplication. python grid = [[0] 3] 3 grid[0][0] = 1 print(grid) What is printed?
- Edge case: lambdas created in a loop (closures). python fs = [lambda: i 10 for i in range(3)] gs = [lambda i=i: i 10 for i in range(3)]…
- Edge case: JavaScript event-loop ordering of synchronous code, a promise callback and a timer. javascript const out = []; out.push("A")…
- Problem: Split an array (duplicates allowed) into the most chunks such that sorting each chunk separately and concatenating gives the…
- Problem: Detect a 132 pattern (i < j < k with a[i] < a[k] < a[j]) in O(n) by scanning from the right with a stack. python def has132(a)…