两个任意大非负整数相加---给某位战友参考

感冒了,两个晚上几乎没睡几天晕乎乎的.今天下午写的,方法可能不大好,是不是完全正确也没详细检查.只是给某位战友参考.

#include <iostream>
using namespace std;

void AddLargeInt(char * strNum1, char * strNum2, char * strRst)
{
 int lenNum1 = strlen(strNum1);
 int lenNum2 = strlen(strNum2);
 char * pLarge = strNum1;  //pLarge指向较大的数
 char * pSmall = strNum2;  //pSmall指向较小的数

 //假设num1比num2大
 int lenLarge = lenNum1;
 int lenSmall = lenNum2;

 if (lenNum2 > lenNum1)
 {
  pLarge = strNum2;
  pSmall = strNum1;
  lenLarge = lenNum2;
  lenSmall = lenNum1;
 }

 int lenRst = lenLarge + 1;
 char * pRst = new char[lenRst + 1];

 pRst[lenRst] = '/0';
 pRst[0] = '0'; //将结果第一位设置为'0'

 char * pRstTra = &pRst[lenRst-1];

 for (int i=lenLarge-1; i>=0; --i) //将较大的字符串复制到结果中
 {
  *pRstTra = pLarge[i];
  --pRstTra;
 }


 int c = 0; //表进位

 //与较小的数进行运算
 pRstTra = &pRst[lenRst-1];
 for (int i=lenSmall-1; i>=0; --i)
 {
  int add = (pSmall[i]-'0') + (*pRstTra -'0') + c;
  c = add / 10;  //进位或不进位

  *pRstTra = add % 10 + '0';  //将本位运算结果放到结果中
  --pRstTra;
 }


 //计算剩下的部分
  while (pRstTra != pRst)
  {
   int add = (*pRstTra -'0') + c;
   c = add / 10;  //进位或不进位

   *pRstTra = add % 10 + '0';
   --pRstTra;
  }
  *pRst = c + '0';


 strcpy(strRst, (pRst[0]=='0')?(pRst+1):pRst );

}
int main()
{
 char d1[100] = {0};
 char d2[100] = {0};
 char rst[120] = {0};

 cout << "请输入两个非负整数:" << endl;
 cin >> d1 >> d2;

 AddLargeInt(d1, d2, rst);

 cout << rst << endl;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值