这是POJ上的一道大整数乘法水题,换了一种算法求解。
以前做大整数乘法的时候,是每乘完一趟,就用一次大整数加法。这次再做大整数乘法,换了一种算法,先统一乘完,再进位。代码简洁了不少。
#include<iostream> #include<stdio.h> #include<string.h> using namespace std; const int Max = 45; int a[Max], b[Max], ans[Max * 2]; char na[Max], nb[Max]; void convert(char *a, int *na) { int len = strlen(a); int index = 0; for(int i=len-1; i>=0; i--) na[index ++] = a[i] - '0'; } int main() { while(scanf("%s%s", na, nb) != EOF) { memset(a, 0, sizeof(a)); memset(b, 0, sizeof(b)); memset(ans, 0, sizeof(ans)); int lenA, lenB; convert(na, a); convert(nb, b); lenA = strlen(na); lenB = strlen(nb); for(int i=0; i<lenA; i++) for(int j=0; j<lenB; j++) { ans[i+j] += a[i] * b[j]; } for(int i=0; i<Max * 2 - 1; i++) { ans[i+1] += ans[i] / 10; ans[i] = ans[i] % 10; } int pos = Max * 2 - 1; while(!ans[pos] && pos >= 0) pos --; if(pos != -1) for(; pos>=0; pos--) printf("%d", ans[pos]); else cout << 0; cout << endl; } system("pause"); return 0; }