/*大整数加法
描述
求两个不超过200位的非负整数的和。
输入
有两行,每行是一个不超过200位的非负整数,可能有多余的前导0。
输出
一行,即相加后的结果。结果里不能有多余的前导0,
即如果结果是342,那么就不能输出为0342。
样例输入
22222222222222222222
33333333333333333333
样例输出
55555555555555555555
*/
#include <iostream>
#include <cstring>
#include <cstdio>
using namespace std;
//打印大整数的程序,不能最打出前面的0
void PrintBigInt1(char *number)
{
int nLength = strlen(number);
int i = 0;
while(i<=nLength-1&&number[i]=='0')
{
i++;
}
if(i==nLength)
{
cout<<0;
return;
}
else
{
for(;i<=nLength-1;i++)
cout<<number[i];
}
return;
}
char* add(const char *number1,const char *number2)
{
int nLength1 = strlen(number1),nLength2 = strlen(number2);
int nLength3= nLength1>nLength2?nLength1:nLength2;
nLength3 = nLength3+1;//两个数相加位数可能增加一位
char *number3 = new char[nLength3+1];
memset(number3,'0',nLength3);
number3[nLength3]='\0';
int bit1 = 0,bit2 =0,jinWei = 0,bit3=0;
int index1 =nLength1-1,index2 = nLength2-1,index3 = nLength3-1;//标记运算位
for(;index1>=0 && index2>=0;index1--,index2--,index3-- )
{
bit1 = number1[index1]-'0';
bit2 = number2[index2]-'0';
bit3 = bit1+bit2+jinWei;
if(bit3>9){bit3-=10;jinWei=1;}
else
jinWei=0;
number3[index3] = bit3+'0';
}
for(;index1>=0;index1--,index3--)
{
bit1 = number1[index1]-'0';
bit3 = bit1+jinWei;
if(bit3>9){bit3-=10;jinWei=1;}
else
jinWei=0;
number3[index3] = bit3+'0';
}
for(;index2>=0;index2--,index3--)
{
bit2 = number2[index2]-'0';
bit3 = bit2+jinWei;
if(bit3>9){bit3-=10;jinWei=1;}
else
jinWei=0;
number3[index3] = bit3+'0';
}
number3[index3] = jinWei+'0';
return number3;
}
int main()
{
char *myNumber1 = new char[201];
char *myNumber2 = new char[201];
gets(myNumber1);
gets(myNumber2);
char* sum = add(myNumber1,myNumber2);
PrintBigInt1(sum);
delete []sum;
delete []myNumber1;
delete []myNumber2;
return 0;
}
大整数加法
最新推荐文章于 2023-03-09 15:13:35 发布