multiply strings

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;
}
}

Leave a Reply

Your email address will not be published. Required fields are marked *