string aResult = string(&aOutput[aWriteIndex]);
class Solution {
public:
string multiply(string num1, string num2) {
int aLen1 = num1.length();
int aLen2 = num2.length();
int aMaxLen = max(aLen1, aLen2);
int aNum1[aMaxLen + 1];
int aNum2[aMaxLen + 1];
for (int i = 0; i < aMaxLen; i++) {
aNum1[i] = 0;
aNum2[i] = 0;
}
for (int i = 0; i < aLen1; i++) {
aNum1[aMaxLen - 1 - i] = int(num1[aLen1 - 1 - i] - '0');
}
for (int i = 0; i < aLen2; i++) {
aNum2[aMaxLen - 1 - i] = int(num2[aLen2 - 1 - i] - '0');
}
//grid
int aGridWidth = aMaxLen * 2;
int aGridHeight = aMaxLen * 2;
int aGrid[aGridWidth][aGridHeight];
for (int i = 0; i < aGridWidth; i++) {
for (int j = 0; j < aGridHeight; j++) {
aGrid[i][j] = 0;
}
}
//caculate grid
int aCarry = 0, aWriteIndex = 0;
for (int aDigit2 = aMaxLen - 1; aDigit2 >= 0; aDigit2--) {
aCarry = 0;
aWriteIndex = aGridWidth - aMaxLen + aDigit2;
for (int aDigit1 = aMaxLen - 1; aDigit1 >= 0; aDigit1--) {
int aProduct = aNum1[aDigit1] * aNum2[aDigit2] + aCarry;
aGrid[aWriteIndex--][aDigit2] = (aProduct % 10);
aCarry = aProduct / 10;
}
while (aCarry % 10 != 0) {
aGrid[aWriteIndex--][aDigit2] = (aCarry % 10);
aCarry /= 10;
}
}
//caculate output
char aOutput[aGridWidth + 1];
aOutput[aGridWidth] = 0;
aWriteIndex = aGridWidth - 1;
for (int i = aGridWidth - 1; i >=0; i--) {
int aSum = aCarry;
for (int j = 0; j < aGridHeight; j++) {
aSum += aGrid[i][j];
}
aOutput[aWriteIndex--] = char((aSum % 10) + '0');
aCarry = (aSum / 10);
}
while (aCarry != 0) {
aOutput[aWriteIndex--] = char((aCarry % 10) + '0');
aCarry /= 10;
}
//Prevent underflow.
if (aWriteIndex < 0) {
aWriteIndex = 0;
}
//Chop off the leading zeroes...
while (aWriteIndex < (aGridWidth - 1) && aOutput[aWriteIndex] == '0') {
aWriteIndex += 1;
}
//Inset by our chopped zeroes...
string aResult = string(&aOutput[aWriteIndex]);
return aResult;
}
};