Data Structures & AlgorithmsModerateAccenture · Cognizant coding round pattern
Problem: Multiply two non-negative integers given as decimal strings without converting them to int; digit i·j lands in position i + j + 1 of the result buffer.
Problem: Multiply two non-negative integers given as decimal strings without converting them to int; digit i·j lands in position i + j + 1 of the result buffer.
def mul(a, b):
res = [0] * (len(a) + len(b))
for i in range(len(a) - 1, -1, -1):
for j in range(len(b) - 1, -1, -1):
p = int(a[i]) * int(b[j]) + res[i + j + 1]
res[i + j + 1] = p % 10; res[i + j] += p // 10
return "".join(map(str, res)).lstrip("0") or "0"
print(mul("99", "99"), mul("123", "0"), mul("25", "4"))What is printed?- A. 9801 0 0100
- B. 9801 000 100
- C. 981 0 100
- D. 9801 0 100
Correct answer: D. 9801 0 100
A product of an m-digit and an n-digit number has at most m + n digits, so the buffer never overflows. Carries move into res[i + j]. Leading zeros are stripped, but an all-zero result must still return "0" (the 'or' handles 123 × 0). O(m·n).
More Coding Interview Problems questions
- Problem: Reverse the bit order of an 8-bit value (bit 0 ↔ bit 7, …). python def rev8(x): r = 0 for in range(8): r = (r << 1) | (x & 1); x…
- Problem: Java int shifts: arithmetic >> keeps the sign, logical >>> fills with zeros, and shifting into the sign bit overflows. java int a…
- Problem: Compute the Z-array (z[i] = length of the longest common prefix of s and s[i:]) in O(n), then use it on pattern + '' + text to…
- Problem: Count non-empty substrings with equal numbers of 0s and 1s where all 0s are grouped together and all 1s are grouped together…
- Problem: Find the lexicographically smallest rotation of a string in O(n) with a two-candidate comparison (Booth-style), and compare it…
- Problem: Compute the bitwise AND of every integer in [m, n] in O(log n): it is the common binary prefix of m and n followed by zeros…