BigInteger类表示不超过1000位的无符号大整数。试重载>>
,<<
和*
,以支持无符号大整数的输入、输出与乘法。
重载面向BigInteger类对象的运算符:
>>
<<
*
裁判测试程序样例:
#include <iostream>
#include <string>
using namespace std;
/* 请在这里填写答案 */
int main()
{
BigInteger a, b, c;
cin >> a >> b;
c = a * b;
cout << a << "*" << b << "=" << c << endl;
return 0;
}
输入样例:
123456789
987654321
输出样例:
123456789*987654321=121932631112635269
代码实现:
没有满分的。。。
class BigInteger{
public:
BigInteger(){}
friend ostream& operator<<(ostream &ou,BigInteger &a);
friend istream& operator>>(istream &in,BigInteger &a);
friend BigInteger operator*(BigInteger &a,BigInteger &b);
string aa;
int na[1002],re[2005],l;
};
ostream& operator<<(ostream &ou,BigInteger &a){
for(int i=a.l-1;i>=0;i--)
ou<<a.re[i];
return ou;
}
istream& operator>>(istream &in,BigInteger &a){
cin>>a.aa;
// cout<<a.aa<<endl;
a.l=a.aa.length();
for(int i=0;i<a.l;i++)
a.re[i]=a.na[i]=(a.aa[a.l-1-i]-'0');
return in;
}
BigInteger operator*(BigInteger &a,BigInteger &b){
BigInteger c;
c.l=a.l+b.l;
for(int i=0;i<a.l;i++)
for(int j=0;j<b.l;j++)
c.re[i+j]+=a.na[i]*b.na[j];
while(c.re[c.l]==0)
c.l--;
for(int i=0;i<c.l;i++){
c.re[i+1]+=c.re[i]/10;
c.re[i]=c.re[i]%10;
}
if(c.re[c.l]!=0) c.l++;
return c;
}
满分(借鉴别人的来纠错)
class BigInteger
{
private:
string str;
public:
BigInteger() {}
BigInteger(string s)
{
str=s;
}
friend ostream&operator<<(ostream &os, BigInteger &bigint)
{
os<<bigint.str;
return os;
}
friend istream&operator>>(istream &is,BigInteger &bigint)
{
is>>bigint.str;
return is;
}
friend BigInteger operator*( BigInteger &bigint1, BigInteger &bigint2);
};
string reserve(string s)
{
int l=s.length();
int j=l-1;
char temp;
for(int i=0; i<l/2; i++,j--)
{
temp=s[i];
s[i]=s[j];
s[j]=temp;
}
return s;
}
BigInteger operator*( BigInteger &bigint1, BigInteger &bigint2)
{
string a=reserve(bigint1.str);
string b=reserve(bigint2.str);
if(bigint1.str[0]=='0' || bigint2.str[0]=='0')
{
string st="0";
return BigInteger(st);
}
int m,n;
int *c=new int[a.length()+b.length()+2]();
for(m=0; m<a.length(); m++)
{
for(n=0; n<b.length(); n++)
{
c[m+n]+=(a[m]-'0')*(b[n]-'0');
}
}
m--;
n--;
int carry=0;
char *ch=new char[a.length()+b.length()+5];
int p;
for( p=0; p<=m+n; p++)
{
if(c[p]>9)
{
ch[p]=(c[p]+carry)%10+'0';
carry=(c[p]+carry)/10;
}
else
{
if(carry+c[p]>9)
{
ch[p]=(carry+c[p])%10+'0';
carry=(carry+c[p])/10;
}
else
{
ch[p]=carry+c[p]+'0';
carry=0;
}
}
}
if(carry>0)
{
ch[p]=carry+'0';
ch[++p]='\0';
}
else
ch[p]='\0';
string st(ch);
string s =reserve(st);
return BigInteger(s);
}