Data Structures & AlgorithmsHardProduct Company SDE · Amazon/Microsoft-style OA

Problem: Sum the prices of n = 100000 items, each 50000, in Java.

Problem: Sum the prices of n = 100000 items, each 50000, in Java.
int n = 100000, price = 50000;
int total = n * price;
long total2 = n * price;
long total3 = (long) n * price;
System.out.println(total + " " + total2 + " " + total3);
What is printed?
  1. A. 5000000000 5000000000 5000000000
  2. B. 705032704 5000000000 5000000000
  3. C. 705032704 705032704 5000000000
  4. D. -705032704 705032704 5000000000

Correct answer: C. 705032704 705032704 5000000000

n * price is computed in 32-bit int and overflows (5 × 10⁹ mod 2³² = 705032704) BEFORE it is widened, so assigning to a long does not help. Casting one operand to long first makes the multiplication 64-bit. Constraints like 10⁵ × 10⁵ demand long.

More Coding Interview Problems questions

Exams that ask this topic