Given two numbers represented as strings, return multiplication of the numbers as a string.
Note: The numbers can be arbitrarily large and are non-negative.
string multiply(string num1, string num2) {
if (!num1.compare(“0”) || !num2.compare(“0”)) return “0”;
int len1 = num1.length();
int len2 = num2.length();
string result(len1+len2, ‘0’);
int tmp, carry;
int i, j;
for (j = len2-1; j >= 0; j–) {
carry = 0;
for (i = len1-1; i >= 0; i–) {
tmp = (num1[i]-‘0’) * (num2[j]-‘0’) + carry + (result[i+j+1]-‘0’);
carry = tmp / 10;
result[i+j+1] = (tmp % 10) + ‘0’;
}
result[j] = carry + ‘0’;
}
if (result[0] == ‘0’) {
return string(result.begin()+1, result.end());
}
else {
return result;
}
}
Resolving technical problems:
Solve your technical problems instantly
We provide Remote Technical Support from Monday to Sunday, 7:00PM to 1:00 AM
Mail your problem details at [email protected] along with your mobile numberand we will give you a call for further details. We usually attend your problems within 60 minutes and solve it in maximum 2 days.