Data Structures & AlgorithmsVery hardAmazon · Microsoft OA
Edge case: Java's int arithmetic wraps around in two's complement. The Python code below emulates exactly what this Java line computes: int lo = 2000000000, hi = 2100000000; int mid = (lo + hi) / 2;
Edge case: Java's int arithmetic wraps around in two's complement. The Python code below emulates exactly what this Java line computes:
`int lo = 2_000_000_000, hi = 2_100_000_000; int mid = (lo + hi) / 2;`
def to_int32(x):
x &= 0xFFFFFFFF
return x - (1 << 32) if x >= 1 << 31 else x
lo, hi = 2_000_000_000, 2_100_000_000
s = to_int32(lo + hi)
mid = int(s / 2) # Java division truncates toward zero
print(mid)What is printed?- A. 2050000000
- B. -97483648
- C. -194967296
- D. 1952516352
Correct answer: B. -97483648
lo + hi = 4.1 × 10⁹ exceeds 2³¹ − 1 and wraps to 4,100,000,000 − 2³² = −194,967,296; dividing by 2 gives −97,483,648, a negative index. Writing lo + (hi − lo) / 2 or (lo + hi) >>> 1 avoids the overflow.
More Coding Interview Problems questions
- Edge case: Array sorting and parseInt in JavaScript. javascript console.log([3, 20, 100].sort().join(","), [1, 2…
- Problem: Answer sub-rectangle sum queries on a matrix in O(1) each with a 2-D prefix-sum table. python m = [[3, 0, 1, 4], [5, 6, 3, 2]…
- Problem: A van with fixed capacity picks up and drops passengers; trip [n, from, to] carries n passengers from km 'from' to km 'to' (they…
- Problem: Start at index 0 and finish at the last index; from i you may jump to any of i+1..i+k. Maximise the sum of visited values…
- Problem: Move from the top-left to the bottom-right cell of a height grid (4 directions). The effort of a route is the largest absolute…
- Problem: n computers and a list of cables. You may unplug any cable and reconnect it elsewhere. Find the minimum number of moves to…