#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAXl (100+1)
int _isNum(const char *num)
{
for (; *num; num++)
{
if ((*num > '9') || (*num < '0'))
return 0;
}
return 1;
}
char *_add(char *result, int resultLen, char *s, int sLen)
{
char *p1=result+resultLen-1;
char *p2=s+sLen-1;
for (; p1>=result && p2>=s; p1--, p2--)
*p1 += *p2-'0';
return result;
}
char *_Carry(char *result, int resultLen)
{
char *p=result+resultLen-1;
for (; p>=result; p--)
{
if (*p >= 10)
{
*(p-1) += 1;
*p = *p-10;
}
*p = *p+'0';
}
if (*result == '0')
{
*result = 0;
strcat(result, result+1);
}
return result;
}
char *plus(char *s1, char *s2)
{
int s1Len = strlen(s1);
int s2Len = strlen(s2);
int resultLen
= 1 + (s1Len>s2Len?s1Len:s2Len);
char *result = (char*)calloc(resultLen+1, sizeof(char));
_add(result, resultLen, s1, s1Len);
_add(result, resultLen, s2, s2Len);
_Carry(result, resultLen);
return result;
}
int main()
{
char s1[MAXl], s2[MAXl];
printf("被加数:"); gets(s1);
printf("加数:"); gets(s2);
if (!_isNum(s1)) return 0;
if (!_isNum(s2)) return 0;
char *ans = plus(s1, s2);
printf("和:"); puts(ans);
free(ans);
return 0;
}