43. Multiply Strings
Asked at 19Meta49Microsoft40Bloomberg37Amazon37Google33Pinterest57Nielsen100X94Two Sigma93Roku87MakeMyTrip65Zoho60ByteDance59EPAM Systems51Palo Alto Networks50TikTok46Salesforce28tcs27Oracle27
Problem
num1 and num2 are non-negative integers written as strings. Return their product as a string, without converting the whole inputs to integers or using big-integer libraries.
Example: "123" × "456" → "56088"
Constraints: lengths ≤ 200.
Digit i of a times digit j of b lands at positions i + j (carry) and i + j + 1. Accumulate into an array of length m + n, then strip leading zeros.
1 2 3
× 4 5
---------
pos: 0 1 2 3 4 3*5 -> pos[3,4], 2*5 -> pos[2,3], ...
result 5 5 3 5 = 5535
Complexity: O(m·n).
class Solution:
def multiply(self, num1: str, num2: str) -> str:
m, n = len(num1), len(num2)
pos = [0] * (m + n)
for i in range(m - 1, -1, -1):
for j in range(n - 1, -1, -1):
s = int(num1[i]) * int(num2[j]) + pos[i + j + 1]
pos[i + j + 1] = s % 10
pos[i + j] += s // 10
res = "".join(map(str, pos)).lstrip("0")
return res or "0"
assert Solution().multiply("2", "3") == "6"
assert Solution().multiply("123", "456") == "56088"
assert Solution().multiply("0", "52") == "0"
class Solution {
public String multiply(String num1, String num2) {
int m = num1.length(), n = num2.length();
int[] pos = new int[m + n];
for (int i = m - 1; i >= 0; i--)
for (int j = n - 1; j >= 0; j--) {
int s = (num1.charAt(i) - '0') * (num2.charAt(j) - '0') + pos[i + j + 1];
pos[i + j + 1] = s % 10;
pos[i + j] += s / 10;
}
StringBuilder sb = new StringBuilder();
for (int d : pos) if (sb.length() > 0 || d != 0) sb.append(d);
return sb.length() == 0 ? "0" : sb.toString();
}
}
func multiply(num1 string, num2 string) string {
m, n := len(num1), len(num2)
pos := make([]int, m+n) // digit i*j lands in pos[i+j+1], its carry in pos[i+j]
for i := m - 1; i >= 0; i-- {
for j := n - 1; j >= 0; j-- {
s := int(num1[i]-'0')*int(num2[j]-'0') + pos[i+j+1]
pos[i+j+1] = s % 10
pos[i+j] += s / 10
}
}
var sb strings.Builder
for _, d := range pos {
if sb.Len() > 0 || d != 0 { // skip leading zeros
sb.WriteByte(byte('0' + d))
}
}
if sb.Len() == 0 {
return "0"
}
return sb.String()
}