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