【题目24】大数乘法

声明: 此解法搜索自互联网,非原创,欲了解详细请参考

http://www.cnblogs.com/hoodlum1980/archive/2007/08/15/857067.html

 

这道题也是一道经常考的题目,解法其实很简单,利用三个整形数组,两个数组A和B分别

存储两个字符串对应的每一位数字,数组C存储A和B两个数组的乘积。计算方法:

C[i+j] += A[i] *B[j];

然后计算进位和进位后每一位的数字值。计算方法:

C[i+1] = C[i] / 10;

C[i] = C[i] % 10;

 

详细的代码见下面:

#include <stdio.h> #include <stdlib.h> #include <string.h> #define N 100 void CharsToInts(char *s, int *a) { int len = strlen(s); int i; for(i = 0; i < N; i++) a[i] = 0; for(i = 0; i < len; i++) { char c = s[i]; a[len-i-1] = c - '0'; } } void MultiplyBigInt(int* a,int* b,int* c) { int i; for(i = 0; i < 2*N; i++) c[i] = 0; for(i = 0; i < N; i++) for(int j = 0; j < N; j++) c[i+j] += a[i] * b[j]; for(i = 0; i < 2*N -1; i++) { c[i+1] += c[i] / 10; c[i] = c[i] % 10; } } int main() { char s1[N],s2[N]; int a[N],b[N],c[N*2]; printf("Input a:"); scanf("%s",s1); printf("Input b:"); scanf("%s",s2); CharsToInts(s1,a); CharsToInts(s2,b); MultiplyBigInt(a,b,c); int i = N*2 -1; while(c[i] == 0) i--; printf("The result of the multiply of a and b is: "); while(i >= 0) printf("%d",c[i--]); printf("/n"); return 0; }

 

你可能感兴趣的:(c,互联网,存储,input)