[原创] 南开的超级大数求和C++版
#include<iostream>#include<cstring>
using namespace std;
class SupperNum
{
public:
SupperNum();
~SupperNum();
void Plus(); //接口与实现分离
void dump() const; //打印超级大数求和结果
void scan();
protected:
int get_a() const; //超级大数a的长
int get_b() const; //超级大数b的长
int get_sum() const; //求和后的数的长
enum{Maxsize=100};
private:
void Core_Sum(); //核心函数
char *a;
char *b;
char *sum;
int flag; //进位标志
};
SupperNum::SupperNum()
{
a = new char[Maxsize+1];
b = new char[Maxsize+1];
sum = new char[Maxsize+2];
flag = 0; //不进位为0
}
SupperNum::~SupperNum()
{
delete [] a;
delete [] b;
delete [] sum;
}
inline int SupperNum::get_a() const { return strlen(a); }
inline int SupperNum::get_b() const { return strlen(b); }
inline int SupperNum::get_sum() const { return strlen(sum); }
void SupperNum::dump() const
{
int i;
for(i=get_sum()-1;i>=0;i--)
cout<<sum[i];
cout<<endl;
}
void SupperNum::scan()
{
cin>>a>>b;
}
void SupperNum::Plus()
{
Core_Sum();
}
void SupperNum::Core_Sum()
{
int s=-1;
int len=0;
int i,j,k;
if(get_a()>get_b())
{
b[len=get_a()] = '\0';
for( i=get_a()-1,j=get_b()-1;i>=0;--i,--j)
if(j>-1) b[i] = b[j];
else b[i] = '0';
}
else
{
a[len=get_b()] = '\0';
for(int i=get_b()-1,j=get_a()-1;i>=0;--i,--j)
if(j>-1) a[i] = a[j];
else a[i] = '0';
}
for(k=len-1;k>=0;--k)
{
if(a[k]-48+b[k]-48>=10) //判断是否进位
{
if(flag == 1) //判断是否连续进位
{
sum[++s] = (a[k]-48+b[k]-48)%10+49;
flag = 1;
}
else
{
sum[++s] = (a[k]-48+b[k]-48)%10+48;
flag = 1;
}
}
else
{
if(a[k]-48+b[k]-48==9) //两数为9的特殊情况
{
if(flag==1)
{
sum[++s] = (a[k]-48+b[k]-48+1)%10+48;
flag = 1;
}
else
sum[++s] = (a[k]-48+b[k]-48)%10+48;
}
else
{
if(flag == 1)
{
sum[++s] = (a[k]-48+b[k]-48)%10+49;
flag = 0;
}
else
sum[++s] = (a[k]-48+b[k]-48)%10+48;
}
}
}
if(flag == 1) sum[++s] = 49;
sum[++s] = '\0';
}
int main()
{
SupperNum obj;
obj.scan();
obj.Plus();
obj.dump();
return 0;
}