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?
  1. A. 2050000000
  2. B. -97483648
  3. C. -194967296
  4. 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

Exams that ask this topic