The problem requires you to multiply two non-negative integers represented as strings and return the product, also as a string. You should not use any built-in libraries for large integers such as Python’s int
or decimal
. The input strings consist of numeric characters only and do not contain any leading zeros, except when the input string is “0”.
To simulate the multiplication of two large integers represented as strings, we can employ a technique that mimics the manual multiplication taught in elementary school:
def multiply(num1: str, num2: str) -> str:
if num1 == "0" or num2 == "0":
return "0"
len1, len2 = len(num1), len(num2)
# Result can be at most len1 + len2 digits
result = [0] * (len1 + len2)
# Reverse both strings to simplify position handling
num1, num2 = num1[::-1], num2[::-1]
# Multiply each digit and add to result
for i in range(len1):
for j in range(len2):
digit_mul = int(num1[i]) * int(num2[j])
result[i + j] += digit_mul
# Handle carry over to the next position
result[i + j + 1] += result[i + j] // 10
result[i + j] %= 10
# Convert result to string and remove leading zeros
while len(result) > 1 and result[-1] == 0:
result.pop()
return ''.join(map(str, result[::-1]))
# Example usage
num1 = "123"
num2 = "456"
print(multiply(num1, num2)) # Output: "56088"
num1
and (m) is the length of num2
. This is because we have nested loops iterating over each digit of both numbers.Got blindsided by a question you didn’t expect?
Spend too much time studying?
Or simply don’t have the time to go over all 3000 questions?