Difficulty: Medium
Given two non-negative integers num1 and num2 represented as strings, return the product of num1 and num2.
Note:
The length of both num1 and num2 is < 110.
Both num1 and num2 contains only digits 0-9.
Both num1 and num2 does not contain any leading zero.
You must not use any built-in BigInteger library or convert the inputs to integer directly.
c语言:
char* multiply(char* num1, char* num2) {
int l1 = strlen(num1);
int l2 = strlen(num2);
//两数相乘,如最高位有进位则结果为l1+l2位数,无进位则为l1+l2-1位数
int* r = (int*)malloc((l1+l2)*sizeof(int));
//memset(r, 0, sizeof(r));//初始化为0,以字节为单位
int i, j;
for (i = 0; i<l1+l2; i++) r[i] = 0; // 第一次更改
for(i = 0; i<l1; i++) {
for(j = 0; j < l2; j++) {
r[i+j] += (int)(num1[l1-i-1]-'0') * (int)(num2[l2-j-1]-'0');
}
}
int carry = 0;
for(i = 0; i < l1+l2; i++) {
r[i] += carry;
carry = r[i]/10;
r[i] = r[i]%10;
}
i = l1+l2-1;
while(r[i] == 0 && i>= 0) {
i--;
}
if(i<0) {
return "0";
} else {
char* answer = (char*)malloc((l1+l2+1)*sizeof(char));
//第二次更改,将开辟的char数组大小由l1+l2改为了l1+l2+1;
for(j = 0; i>=0; i--, j++) {
answer[j] = r[i]+'0';
}
answer[j] = '\0';
return answer;
}
}
第一次提交之后的错误是乘法运算上的不正确,
Input:
"237"
"284"
Output:
"72208"
Expected:
"67308"
但是这时已经通过了205个测试样例,显然不是算法上的错误,于是我尝试着更改了数组初始化的内容,将memset改为了使用for循环初始化,
memset是对内存中连续的一块地址以字节为单位进行赋值,数组的每个int元素一般是4个字节,所以只能用memset初始化为0或-1(因为-1的补码全是1)。但是我不明白我这里明明是初始化为0也会导致不正确!!!(求大神指点)
改为for循环之后,出错的地方变成了以下:
Input:
"498828660196"
"840477629533"
Output:
"419254329864656431168468A"
Expected:
"419254329864656431168468"
检查后发现是我的字符数组大小开辟小了一位,因为末尾还要加终止符’\0’,所以应该是l1+l2+1的大小,其实用i+2更准确.
修改后通过。