高精乘就是两个比较大的数字相乘,结果超过了基本类型的表示范围,所以不能直接用普通的数据类型相乘,所以我们要用字符串来表示,所以我们来用STL里的string来表示字符串.
#include<iostream>
using namespace std;
#include<string>
#define MAXLEN 100
string sum(string &a, string &b)
{
reverse(a.begin(), a.end()); //高精加是把最高位位循环
reverse(b.begin(), b.end());
string s;
int n1[MAXLEN] = {0}; //放a
int n2[MAXLEN] = { 0 }; //放b
int tmp[MAXLEN] = { 0 }; //放最终的
for (int i = 0; i < a.size(); i++)
{
n1[i] = a[i] - '0';
}
for (int i = 0; i < b.size(); i++)
{
n2[i] = b[i] - '0';
}
int sum = 0;
int maxlen = a.size() > b.size() ? a.size() : b.size();
int j;
for ( j = 0; j < maxlen; j++)
{
sum = n1[j] + n2[j] + tmp[j];
tmp[j] = sum % 10;
tmp[j + 1] = sum / 10;
}
j--;
j += tmp[j+1];
while (j>=0)
{
s.push_back(tmp[j] + '0');
j--;
}
return s;
}
string mul(string &a, string &b)
{
string s;
if (a.size()==0 || b.size()==0)
{
return s;
}
reverse(a.begin(), a.end()); //高精乘无所谓
reverse(b.begin(), b.end());
int n1[MAXLEN] = { 0 }; //放长的
int n2[MAXLEN] = { 0 }; //放短的.
int tmp[MAXLEN] = { 0 }; //放最终的
for (int i = 0; i < a.size(); i++)
{
n1[i] = a[i] - '0';
}
for (int i = 0; i < b.size(); i++)
{
n2[i] = b[i] - '0';
}
int n1_size = a.size();
int n2_size = b.size();
int sum = 0;
int i, j;
for ( i = 0; i < n1_size; i++)
{
for (j = 0; j < n2_size; j++)
{
sum = n1[i] * n2[j] + tmp[i + j];
tmp[i + j] = sum % 10;
tmp[i + j + 1] += sum / 10;
}
}
int size=i+j-1-1+tmp[i+j-1];
while (size >= 0)
{
s.push_back(tmp[size] + '0');
size--;
}
return s;
}
int main()
{
string a, b;
cin >> a >> b;
//cout << sum(a, b);
cout << mul(a, b);
system("pause");
return 0;
}