本文的代码思想和代码写法参考 http://www.2cto.com/kf/201505/399706.html
已编译成功
</pre><pre name="code" class="cpp">
#include <iostream>
using namespace std;
class BigNumMutliplie{
private:
char num_a[100];
char num_b[100];
int len_a;
int len_b;
bool negative;
bool detect_num()//检验数组特殊情况
{
len_a=strlen(num_a);
len_b=strlen(num_b);
if(len_a==0||len_b==0)
{
return false;
}
for(int i=0;i<len_a;i++)
{
if(!(num_a[i]>='0'&&num_a[i]<='9'))
{
return false;
}
}
for(int i=0;i<len_b;i++)
{
if(!(num_b[i]>='0'&&num_b[i]<='9'))
{
return false;
}
}
}
public:
BigNumMutliplie()//构造函数实现初始化
{
memset(num_a,0,sizeof(num_a));//置0
memset(num_b,0,sizeof(num_b));
len_a=0;
len_b=0;
}
bool init_num(const char* num_a,const char* num_b)
{
this->negative =false;
if(!num_a||!num_b)//num_a或num_b为NULL
{
return false;
}
if(*num_a=='-'||*num_a=='+')
{
if(*num_a=='-')
negative=!negative;
strcpy_s(this->num_a,num_a+1);
}
else
{
strcpy_s(this->num_a,num_a);
}
if(*num_b=='-'||*num_b=='+')
{
if(*num_b=='-')
negative=!negative;
strcpy_s(this->num_b,++num_b);
//strcpy_s(this->num_b,num_b++);error;因为num_b++在拷贝时还未+1
}
else
{
strcpy_s(this->num_b,num_b);
}
}
char *mutliplie_ab()
{
if(!detect_num())//return false
{
return NULL;
}
int *int_res=new int[(len_a+len_b)*sizeof(int)];
//a*b值的位数不会超过a与b的位数之和
char *str_res=new char[(len_a+len_b+2)*sizeof(char)];
//多出来的一位存+-号,一位存\0
memset(int_res,0,(len_a+len_b)*sizeof(int));
memset(str_res,0,(len_a+len_b+2)*sizeof(char));
//相乘是从数组[0]开始的
for(int i=0;i<len_a;i++)
{
for(int j=0;j<len_b;j++)
{
int_res[i+j+1] += (num_a[i]-'0')*(num_b[j]-'0');//第一位预留出来用于保存符进位
}
}
//处理进位,从后往前,即低位开始
for(int index=len_a+len_b-2+1;index>=0;index--)
{
if(int_res[index]>=10)
{
int_res[index-1]+=int_res[index]/10;
int_res[index]=int_res[index]%10;
}
}
int i=0,j=0;
while(int_res[i]==0)//找到开始不为0的位置
{
i++;
}
//str_res首位为负号
if(negative)
{
str_res[j++]='-';
}
//int_res是从首位不为0的位置i到len_a+len_b
//str_res是从首位负号的下一位的位置j到len_a+len_b+1
for(;i<(len_a+len_b)&&j<(len_a+len_b+1);i++,j++)
{
str_res[j]=int_res[i]+'0';
}
str_res[len_a+len_b+1]='\0';
delete[] int_res;
return str_res;
}
};
void main(){
BigNumMutliplie num;
char* num_a="-9999999999999";
char* num_b="999";
char * str_res;
num.init_num(num_a,num_b);
str_res=num.mutliplie_ab();
if(str_res)
{ cout<<sdft<<endl;
cout<<num_a<<" * "<<num_b<<" = "<<str_res<<endl;
delete[] str_res;
}
}