#include <iostream>
#include <stack>
#include <cstring>
using namespace std;
//charadd函数的功能是将字符ch1和字符ch2变为数字相加,再加上进位,
//然后再变为字符返回
char charadd(char ch1, char ch2, bool &carry)
{
int num;
num = ch1 - '0' + ch2 - '0'; //变为两个数字之和
if(carry)
//是否有进位
{
num++;
carry = false;
}
if(num > 9)
//相加大于10,至进位标志为真,调整和
{
carry = true;
num -= 10;
}
return num + '0';
//返回结果字符
}
char * add(const char *num1, const char *num2)
{
char *str;
char ch;
int i, j;
bool carry;
stack<char> chstack;
i = strlen(num1) - 1;
//指向num1的个位
j = strlen(num2) - 1;
//指向num2的个位
carry = false;
while(i >= 0 && j >= 0)
//两个字符串从个位开始相加
{
ch = charadd(num1[i--], num2[j--], carry);
chstack.push(ch);
}
while(i >= 0)
//num1数位长,把剩余的数字加上
{
ch = charadd(num1[i--], '0', carry);
chstack.push(ch);
}
while(j >= 0)
//num2数位长,把剩余的数字加上
{
ch = charadd('0', num2[j--], carry);
chstack.push(ch);
}
// 利用栈将结果输入到结果字符串str中
j = chstack.size( );
str = new char[j + 1];
for(i = 0; i < j; i++)
{
str[i] = chstack.top( );
chstack.pop( );
}
str[i] = '\0';
return str;
}
int main( )
{
char s1[ ] = "134253600000000";
char s2[ ] = "321411145562442";
char *str = add(s1, s2);
cout << s1 << " + " << s2 << " = " << str << endl;
delete [ ]str;
return 0;
}