A*B Problem
题目背景
高精度乘法模板题。
题目描述
给出两个非负整数,求它们的乘积。
输入格式
输入共两行,每行一个非负整数。
输出格式
输出一个非负整数表示乘积。
样例 #1
样例输入 #1
1
2
样例输出 #1
2
提示
每个非负整数不超过 1 0 2000 10^{2000} 102000。
题解-来自Pleasant_goat_17
#include<iostream>
#include<string>
using namespace std;string Add(string a,string b){if(a.length()<b.length()){string tmp = a;a = b;b = tmp;}int alen = a.length();int blen = b.length();for(int i=0;i<alen-blen;i++){b = '0'+b;}int up=0,num;string ans;for(int i=alen-1;i>=0;i--){num = (a[i]-'0')+(b[i]-'0')+up;up = num/10;num%=10;ans = (char)(num +'0') + ans;}if(up){ans = (char)(up+'0') + ans;}return ans;
}string Mult(string a,string b){int alen = a.length();int blen = b.length();string ans="0";string tmp;int num,up=0;for(int i=alen-1;i>=0;i--){tmp = "";for(int j=blen-1;j>=0;j--){num = (a[i]-'0')*(b[j]-'0')+up;up = num/10;num%=10;tmp = (char)(num+'0')+tmp;}if(up){tmp = (char)(up+'0')+tmp;up=0;}// cout << a[i] << "*" << b << "=" << tmp << endl;for(int k=0;k<(alen-1)-i;k++){tmp = tmp + '0';// cout << tmp << endl;}// cout << ans << "+" << tmp << endl;ans = Add(ans,tmp);}int index=0;while(1){//去0if(index == ans.length()-1){ans = "0";break;}if(ans[index]!='0'){ans = ans.substr(index,ans.length());break;}index++;}return ans;
}int main()
{string a,b;cin >> a >> b;// cout << Add(a,b)<<endl;cout << Mult(a,b);
}