简单的大数相乘,直接套上模板即可,注意一下数组开大点,不然肯定WA。
代码:
#include<iostream> #include<cstdio> #include<cstring> using namespace std; int sum[2001]; int s1[50] , s2[50]; string str1 , str2; void multiply() { int i , j , k; int l1 , l2 , len; memset(sum,0,sizeof(sum)); memset(s1,0,sizeof(s1)); memset(s2,0,sizeof(s2)); l1 = str1.size(); l2 = str2.size(); for(i = l1-1 , k = 1;i >= 0;i-- , k++) s1[k] = str1[i]-48; for(i = l2-1 , k = 1;i >= 0;i-- , k++) s2[k] = str2[i]-48; for(i = 1;i <= l1;i++ ) { for(j = 1;j <= l2;j++) { sum[i+j-1] += s1[i]*s2[j]; sum[i+j] += sum[i+j-1]/10; sum[i+j-1] %= 10; } } len = 2000; while(len--) { if(sum[len] != 0) break; } for(;len >= 1;len--) cout<<sum[len]; cout<<endl; } int main() { while(cin>>str1>>str2) { multiply(); } return 0; }
时间: 2024-09-21 16:13:46