Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
Note: You must not use any built-in BigInteger library or convert the inputs to integer directly.
Test Cases
Example 1:
Input: num1 = "2", num2 = "3"
Output: "6"
Example 2:
Input: num1 = "123", num2 = "456"
Output: "56088"
Constraints:
-
1 <= num1.length, num2.length <= 200
-
num1
andnum2
consist of digits only. -
Both
num1
andnum2
do not contain any leading zero, except the number0
itself.
Solution
class Solution {
public:
string multiply(string num1, string num2) {
if (num1 == "0" || num2 == "0") return "0";
int n1 = num1.size(), n2 = num2.size();
vector<int> result(n1+n2, 0);
for(int i=n1-1; i>=0; i--) {
for(int j=n2-1; j>=0; j--) {
int mult = (num1[i] - '0')*(num2[j] - '0');
int sum = mult + result[i + j + 1];
result[i + j + 1] = sum % 10;
result[i + j] += sum / 10;
}
}
int i = 0;
while(i < result.size() && result[i] == 0) {
i++;
}
string res = "";
while(i < result.size()) {
res.push_back(result[i++] + '0');
}
return res;
}
};
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 mul = (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
int p1 = i + j, p2 = i + j + 1;
int sum = mul + pos[p2];
pos[p1] += sum / 10;
pos[p2] = (sum) % 10;
}
}
StringBuilder sb = new StringBuilder();
for(int p : pos) if(!(sb.length() == 0 && p == 0)) sb.append(p);
return sb.length() == 0 ? "0" : sb.toString();
}
}
class Solution(object):
def multiply(self, num1, num2):
"""
:type num1: str
:type num2: str
:rtype: str
"""
n, m = len(num1), len(num2)
result = [0] * (n + m)
for i in range(n - 1, -1, -1):
for j in range(m - 1, -1, -1):
mul = (ord(num1[i]) - ord('0')) * (ord(num2[j]) - ord('0'))
sum_ = mul + result[i + j + 1]
result[i + j + 1] = sum_ % 10
result[i + j] += sum_ // 10
product = ''.join(map(str, result)).lstrip('0')
return product if product else "0"