大整数乘法

输入为两个100位以内大整数,输出其结果

例程:输入:1234567 123

输出:151851741

本题思想为:用字符串存储其各位字符,以数学乘法基本计算方法进行相乘进位运算,得出最终结果。


#include

#include
#include
#include

using namespace std;

int main()
{
string str1,str2;
cin>>str1>>str2;                                                          //读取两个整数
int wei1=str1.size(),wei2=str2.size(); //记录整数位数
string strMid(wei1+wei2,'0');
string strLastRst(wei1+wei2,'0'); //大整数乘法结果存储,长度为wei1+wei2
string *strRst=new string[50]; //用于存放单次乘积
//strRst[0]="abcde";
for(int i=wei2-1,j=wei1-1; i>=0; i--)
{
int temp=0; //
for(int m=0; m //
strMid[m]='0'; //初始化
for(j=wei1-1; j>=0; j--)
{
int a=(str1[j]-'0')*(str2[i]-'0')+temp;
strMid[i+j+1]=a%10+'0';
temp=a/10;
}
strMid[i+j+1]=temp+'0';
strRst[wei2-1-i]=strMid;//strcmp(strRst[wei2-1-i],strMid); //存储一次乘积结果
}
for(int j=wei1+wei2-1; j>=0; j--)
{
static int temp=0;
for(int i=0; i{
temp+=strRst[i][j]-'0'; //将wei1次乘积相加
}
strLastRst[j]=temp%10+'0'; //并将和的个位存入相应位,十位进位进行下一步运算
temp=temp/10;
}
int x=0;
while(strLastRst[x++] == '0'); //避免输出最高位为0的情况
x--;
while(strLastRst[x] != '\0')
       cout<       return 0;
}

你可能感兴趣的:(笔试题)