Data Structures & AlgorithmsModerateAmazon · Microsoft OA
Edge case: integer division and modulo with negative operands in Python.
Edge case: integer division and modulo with negative operands in Python.
print(-7 // 2, -7 % 2, int(-7 / 2))What is printed?
- A. -3 -1 -3
- B. -4 -1 -4
- C. -3 1 -4
- D. -4 1 -3
Correct answer: D. -4 1 -3
Python's // floors toward −∞, so −7 // 2 = −4, and % takes the sign of the divisor, so −7 % 2 = 1 (−4 × 2 + 1 = −7). int(−3.5) truncates toward zero, giving −3. C, C++ and Java truncate: −7 / 2 = −3 and −7 % 2 = −1.
More Coding Interview Problems questions
- Problem: Replace at most k characters so that the longest possible substring consists of one repeated letter; return its length. python…
- Problem: Smallest length of a contiguous subarray of POSITIVE integers with sum ≥ target (0 if none). python def minlen(a, t): l, s, best…
- Problem: Return all start indices of anagrams of p inside s using a fixed-size window of letter counts. python from collections import…
- Problem: Intersect two lists of disjoint, sorted closed intervals. python def inter(A, B): i = j = 0; out = [] while i < len(A) and j <…
- Problem: Cars drive toward a target on a one-lane road. A car that catches a slower car ahead joins it as a fleet (moving at the slower…
- Problem: Return the minimum number of parentheses to insert to make a string valid. python def minadd(s): open, add = 0, 0 for c in s: if…