1381 ab
Constraints
Time Limit: 1 secs, Memory Limit: 32 MB
Description
Give two positive integers a and b, please help us calculate ab.
Input
The first line of the input is a positive integer T. T is the number of test cases followed.
Each test case contain two integer a,b (0<=a<=10^100, 0<=b<=10,000) given in one line.
Output
The output of each test case should consist of one line, contain the result of a*b.
Sample Input
1
2 7
Sample Output
14
Problem Source
Algorithm Course Examination 2006
Sicily 1381
由于是大整数,所以我们用数组来存储两个乘数,根据乘法竖式的算法规则,令两个乘数与其乘积的最右边为第一位,则乘积的第m位等于乘数A的第i位和乘数B的第j位(i+j-1=m)加上进位,如果大于10的话该位取模,然后进位是最初所得数字除以10,核心代码如下
#include<iostream>
#include<cstring>
using namespace std;
int a[205];
int b[205];
int c[205];
int main(){
int times;
cin>>times;
while(times--){
memset(a,0,sizeof(a));
memset(b,0,sizeof(b));
memset(c,0,sizeof(c));
string stra,strb;
cin>>stra>>strb;
if(stra=="0"||strb=="0"){
cout<<'0'<<endl;
continue;
}
int lena=stra.size();
int lenb=strb.size();
int counta=1;
int countb=1;
for(int i=lena-1;i>=0;i--){
a[counta++]=stra[i]-'0';
}
for(int i=lenb-1;i>=0;i--){
b[countb++]=strb[i]-'0';
}
// cout<<counta<<' '<<countb<<endl;
int temp;
for(int i=1;i<counta;i++){
int x=0;
for(int j=1;j<countb;j++){
c[i+j-1]=x+c[i+j-1]+a[i]*b[j];
x=c[i+j-1]/10;
c[i+j-1]=c[i+j-1]%10;
// cout<<c[i+j-1]<<' ';
temp=x;
if(j==countb-1){
if(temp!=0){
c[i+j]+=temp;
}
}
}
}
for(int i=105;i>=0;i--){
if(c[i]!=0){
for(int j=i;j>=1;j--){
cout<<c[j];
}
cout<<endl;
break;
}
}
}
}