Data Structures & AlgorithmsModerateProduct Company SDE · Amazon/Microsoft-style OA
Problem: Reverse the digits of a 32-bit signed integer, returning 0 if the result overflows.
Problem: Reverse the digits of a 32-bit signed integer, returning 0 if the result overflows.
def rev(x):
s = -1 if x < 0 else 1
r = int(str(abs(x))[::-1]) * s
return r if -2**31 <= r <= 2**31 - 1 else 0
print(rev(-120), rev(1534236469), rev(-2147483412))What is printed?- A. -21 0 -2143847412
- B. -021 0 -2143847412
- C. -21 9646324351 -2143847412
- D. 21 0 -2143847412
Correct answer: A. -21 0 -2143847412
Trailing zeros vanish (−120 → −21). 1534236469 reversed is 9646324351, above 2³¹ − 1, so 0. −2147483412 reversed is −2143847412, which still fits. In C++/Java you must check before multiplying by 10 (r > INT_MAX/10) because the overflow itself is the bug.
More Coding Interview Problems questions
- 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…
- Problem: Return the excel-style column title for a column number (1 → A, 26 → Z, 27 → AA). python def title(n): s = '' while n: n -= 1 s =…
- Problem: Return the number formed by the most significant digit of the sum of digits repeatedly added until one digit remains (digital…
- Problem: Count pairs (i < j) with a[i] > a[j] (inversions) in an array of n = 2 × 10⁵ values. Which approach runs within a 1-second limit?
- Problem: Answer q = 10⁵ queries 'sum of a[l..r]' on a static array of n = 10⁵ values. Which approach is best?
- Problem: An array of n = 10⁵ values receives 10⁵ operations, each either 'add v to a[i]' or 'sum of a[l..r]'. Which data structure gives…