Multiply Strings Problem: Given two non-negative integers num1
and num2
represented as strings, return the product of num1
and num2
, also represented as a string.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
Example :
Input: num1 = "2", num2 = "3" Output: "6"
Table of Contents
Multiply Strings Problem Solution
Problem Solution In Python
class Solution:
def multiply(self, num1, num2):
num1_num = 0
for each in num1:
asc = ord(each)
num = asc - 48
num1_num = num1_num*10+num
num2_num = 0
for each in num2:
asc = ord(each)
num = asc - 48
num2_num = num2_num*10+num
mul = num1_num * num2_num
if mul == 0:
return '0'
strlist = []
while mul != 0:
digit = mul%10
strlist.append(digit)
mul = (mul- digit)//10
result = ''
for each in strlist:
newstr = chr(each+48)
result = newstr + result
return result
Problem Solution In Java
public String multiply(String num1, String num2) {
if ("0".equals(num1) || "0".equals(num2)) {
return "0";
}
int num1Len = num1.length();
int num2Len = num2.length();
int t;
int[] res = new int[num1Len + num2Len];
for (int i = num1Len - 1; i >= 0; i--) {
for (int j = num2Len - 1, r = num1Len - 1 - i; j >= 0; j--, r++) {
res[r] += (num1.charAt(i) - '0') * (num2.charAt(j) - '0');
if (res[r] > 9) {
t = res[r];
res[r] = t % 10;
res[r + 1] += t / 10 % 10;
}
}
}
StringBuilder sb = new StringBuilder();
for (int i = 0; i < res.length; i++) {
if (sb.length() == 0 && res[res.length - 1 - i] == 0) {
continue;
}
sb.append(res[res.length - 1 - i]);
}
return sb.toString();
}
Problem Solution In C++
class Solution {
public:
string multiply(string num1, string num2) {
int n1 = num1.length(), n2 = num2.length();
if(n1 == 0 || n2 == 0) return "";
string res(n1+n2, '0');
int c = 0;
for(int i = n1-1; i >= 0; i--){
for(int j = n2-1; j >= 0; j--){
int tmp = (num1[i]-'0')*(num2[j]-'0')+c+res[i+j+1]-'0';
res[i+j+1] = tmp%10+'0';
c = tmp/10;
}
res[i] += c;
c = 0;
}
int start = 0;
while(start < res.length() && res[start] == '0')
start++;
if(start == res.length())
return "0";
return res.substr(start);
}
};
Problem Solution In C
char* multiply(char* arg1, char* arg2) {
int len = strlen(arg1) + strlen(arg2);
char *result = malloc(sizeof(char) * (len + 1));
int acc;
int k = 0;
for (int i = 0; i < len+1; i++)
result[i] = '0';
for (int i = strlen(arg1)-1; i >= 0; i--){
for (int j = strlen(arg2)-1; j >= 0; j--){
acc = (arg1[i] - '0') * (arg2[j] - '0') + (result[i + j + 1] - '0');
result[i+j+1] = (acc % 10) + '0';
result[i+j] = ((acc /10) + (result[i + j] - '0')) + '0';
}
}
result[len] = 0;
while (result[k] == '0')
k++;
return strlen(result+k) > 0 ? result+k : "0";
}