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.
Converting the input string to integer is NOT allowed.
You should NOT use internal library such as BigInteger.
說明:模擬手工計算兩個整數的乘積,注意每輪乘積最高位的進位和乘積爲0的情況。
代碼:
char* multiply(char* num1, char* num2) {
char *zero = "0";
if(strcmp(num1, zero) == 0 || strcmp(num2, zero) == 0) return zero;
int len1 = strlen(num1), len2 = strlen(num2);
//逆序存放乘積
char *ret = (char *)malloc(sizeof(char) * (len1+len2+1));
memset(ret, '0', sizeof(char) * (len1+len2+1));
int i = 0, j = 0;
for(i = 0; i <= len1-1; i++)
{
//乘數爲0則跳過這次循環,開始下一次循環
if(num1[len1-1-i] == '0') continue;
int carry = 0;
int n1 = num1[len1-1-i] - '0';
for(j = 0; j <= len2-1; j++)
{
int n2 = num2[len2-1-j] - '0';
int sum = n1 * n2 + ret[i+j] - '0' + carry;
carry = sum / 10;
ret[i+j] = sum % 10 + '0';
}
if(carry) ret[i+len2] = carry + '0';
}
ret[len1+len2] = '\0';
// printf("%s\n", ret);
char *p = ret, *q = &ret[len1+len2-1];
char tmp;
//將逆序的乘積轉換成正序
while(p < q)
{
tmp = *p;
*p = *q;
*q = tmp;
p++;
q--;
}
//如100*100,再ret所指字符數組裏原來存放"000010",翻轉後變成"010000",需要去掉開頭的'0'
if(*ret == '0')
return ret+1;
else
return ret;
}