//first one
string multiply(string num1, string num2) {
int lenA = num1.length();
int lenB = num2.length();
string ret;
int i, j;
int* c = new int[lenA + lenB];
memset(c, 0, sizeof(int) * (lenA+lenB));
for (i = lenA - 1; i >= 0; i--)
for (j = lenB - 1; j >= 0; j--)
c[i + j + 1] += (num2[j] - '0') * (num1[i] - '0');
for (i = lenA + lenB - 1; i >= 0; i--)
{
if (c[i] >= 10)
{
c[i - 1] += c[i] / 10;
c[i] %= 10;
}
}
i = 0;
while ((i < lenA + lenB)&&c[i] == 0)
i++;
if(i==(lenA+lenB))
ret="0";
while (i < lenA + lenB)
{
ret.push_back(c[i] + '0');
i++;
}
delete[] c;
return ret;
}
//second one, by anniekim
string multiply(string num1, string num2) { int N = num1.size(), M = num2.size(); string res(N+M, '0'); for (int i = N - 1; i >= 0; --i) { int carry = 0; for (int j = M - 1; j >= 0; --j) { int sum = carry + (res[i+j+1] - '0') + (num1[i] - '0') * (num2[j] - '0'); res[i+j+1] = sum % 10 + '0'; carry = sum / 10; } res[i] += carry; } while (res.size() > 1 && res[0] == '0') res.erase(res.begin()); return res; } |
No comments:
Post a Comment