昨天上了大三的算法课,学了大整数乘法,上课听得很明白,但回来实现,就有点问题了。。
① 做乘法的时候,要记得减去'0'的ascii码48。
② 存数字的数组要记得从1开始存,如果从0开始存的话,进位时可能会导致越界 - -
③ 进位时,记得要用一个循环,不断进位,这个地方坑了我很久 - -
1 #include <stdio.h> 2 #include <stdlib.h> 3 #include <string.h> 4 #define N 100 5 char number1[N]; 6 char number2[N]; 7 char result[2*N]; 8 9 int main() 10 { 11 printf( "please input the first number: " ); 12 scanf( "%s", number1 ); 13 printf( "please input the next number: " ); 14 scanf( "%s", number2 ); 15 int i, j, len1, len2, p; 16 len1 = strlen(number1); 17 len2 = strlen(number2); 18 for( i=len1; i>0; i-- ) 19 number1[i] = number1[i-1]; 20 for( i=len2; i>0; i-- ) 21 number2[i] = number2[i-1]; 22 memset( result, -1, sizeof(result) ); 23 for( i=1; i<=len1; i++ ) 24 for( j=1; j<=len2; j++ ) 25 { 26 if( result[i+j] == -1 ) 27 result[i+j] = (number1[i]-48)*(number2[j]-48); 28 else 29 result[i+j] += (number1[i]-48)*(number2[j]-48); 30 p = i+j; 31 while( result[p] > 9 ) 32 { 33 if( result[p-1] == -1 ) 34 result[p-1] = result[p]/10; 35 else 36 result[p-1] += result[p]/10; 37 result[p] %= 10; 38 p--; 39 } 40 } 41 42 for( i=1; result[i]!=-1; i++ ) 43 printf( "%d", result[i] ); 44 printf( " " ); 45 system( "pause" ); 46 return 0; 47 }
样例输入
12345678900 98765432100
样例输出
1219326311126352690000
以上的代码是有问题的,没有经过OJ的测试。
① 时间复杂度很高,o(n*n)的复杂度上,还要乘于进位所带来的复杂度!!!
② 没有细细考虑到前置0的情况!!!
1 #include <stdio.h> 2 #include <string.h> 3 #define N 10000 4 char number1[N]; 5 char number2[N]; 6 int result[2*N]; 7 int ans[2*N]; 8 9 int main() 10 { 11 scanf( "%s%s", number1, number2 ); 12 int i, j, len1, len2, p, len; 13 len1 = strlen(number1); 14 len2 = strlen(number2); 15 16 for( i=0; i<len1; i++ ) 17 for( j=0; j<len2; j++ ) 18 result[i+j] += (number1[i]-48)*(number2[j]-48); 19 20 len = len1+len2-2; 21 p = 0; 22 while( len > 0 ) 23 { 24 result[len-1] += result[len]/10; 25 ans[p++] = result[len--]%10; 26 } 27 ans[p] = result[0]; 28 while( ans[p] == 0 ) 29 p--; 30 if( p == -1 ) 31 printf( "0 " ); 32 else 33 { 34 for( ; p>=0; p-- ) 35 printf( "%d", ans[p] ); 36 printf( " " ); 37 } 38 return 0; 39 }