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?
- A. 5000000000 5000000000 5000000000
- B. 705032704 5000000000 5000000000
- C. 705032704 705032704 5000000000
- 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
- Problem: Count primes below n with the sieve of Eratosthenes. python def countprimes(n): if n < 3: return 0 isp = [True] n; isp[0] =…
- Problem: Compute nCr mod p for many queries using precomputed factorials and Fermat inverses (p prime). python M = 109 + 7 N = 20 fact =…
- Problem: Find the GCD of all array elements and the LCM of a pair. cpp long long g(long long a, long long b) { return b == 0 ? a : g(b, a…
- Problem: Count trailing zeros of n! (number of factors 5). python def tz(n): c = 0 while n: n //= 5; c += n return c print(tz(25)…
- Problem: Reverse the digits of a 32-bit signed integer, returning 0 if the result overflows. python def rev(x): s = -1 if x < 0 else 1 r =…
- Problem: Find the integer x (0 ≤ x < m) such that 3x ≡ 1 (mod 11) using the extended Euclidean algorithm. python def ext(a, b): if b == 0…