不限制位数的大数乘法

#include <iostream>
#include <string>
using std::cout;
using std::cin;
using std::string;
using std::ostream;
using std::istream;
class BigNum
{
public:
	friend ostream& operator<<(ostream& os,const BigNum& n);
	friend istream& operator>>(istream& os,BigNum& n);
	BigNum(){}
	BigNum(string v):ValueStr(v){}
	string::size_type GetDigit()
	{
		return ValueStr.length();
	}
	BigNum operator*(BigNum a)
	{
		string rst(a.GetDigit()+GetDigit(),'0');
		string::size_type 
			alen=a.GetDigit(),
			mylen=GetDigit(),
			rslen=rst.length();
		int carry=0;
		int mult=0;
		int rsti=0;
		for (string::size_type ai=alen-1;ai!=-1;ai--)
		{
			for (int myi=mylen-1;myi!=-1;myi--)
			{
				rsti=rslen-alen+ai-mylen+1+myi;
				mult = (ValueStr[myi]-'0')*(a.ValueStr[ai]-'0');
				rst.at(rsti)+=carry+(mult>9?(mult%10):mult);
				if (rst.at(rsti)>'9')
				{
					carry=1;
					rst.at(rsti)-=10;
				}
				else
				{
					carry=0;
				}
				if (mult>9)
				{
					carry+=mult/10;
				}
			}
		}
		if (rst.at(0)=='0')
		{
			rst=rst.substr(1);
		}
		return BigNum(rst);
	}
private:
	string ValueStr;
};
istream& operator>>(istream& is,BigNum& n)
{
	std::getline(is,n.ValueStr);
	return is;
}
ostream& operator<<(ostream& os,const BigNum& n)
{
	os<<n.ValueStr;
	return os;
}
int main()
{
	//手动输入初始化方式:
	//BigNum a,b;
	//cout<<"enter a big number A:\n";
	//cin>>a;
	//cout<<"enter another big number B:\n";
	//cin>>b;
	//cout<<"A*B= "<<a*b;
	// 字符串初始化方式
	BigNum a("4090111111115057122292848555"),
		b("100000000000000000999");
	cout<<a*b;
}

你可能感兴趣的:(C++,C++,算法,大数乘法)