本帖最后由 xiaojuan 于 2014-9-24 22:37 編輯
////////////////////////////////////////////////////
//實現(xiàn)兩個小于64位數(shù)字的加法運算
//作者:豆腐干
//時間:2014年9月23日 15:25:47
////////////////////////////////////////////////////
#include<stdio.h>
#include<string.h>
//字符串翻轉(zhuǎn)函數(shù)
char *strinv(char *def)
{
int len, i;
char *temp1 = def;
char *temp2 = def;
char ch;
while(*temp2 != '\0')
temp2++;
temp2--;
len = strlen(def);
for(i = 0; i < len / 2; i++)
{
ch = *(temp1 + i);
*(temp1 + i) = *(temp2 - i);
*(temp2 - i) = ch;
}
return def;
}
int main(void)
{
char buf1[64] ="123456789123456789123456789123456789123456789123456789123456789";
char buf2[64] ="987654321987654321987654321987654321987654321987654321";
char dest[64 + 1];
printf("add1 = %s\nadd2 = %s\n", buf1, buf2);
char *temp1 = strinv(buf1);
char *temp2 = strinv(buf2);
char *temp3 = dest;
int i, num, len, len1, len2, flag = 0;
len1 = strlen(buf1);
len2 = strlen(buf2);
if(len1 > len2)
{
while(*temp2 != '\0')
temp2++;
for(i = 0; i < len1 - len2; i++)
{
*(temp2 + i) = '0';
}
temp2 = buf2;
len = len1;
}
else if(len1 < len2)
{
while(*temp1 != '\0')
temp1++;
for(i = 0; i < len2 - len1; i++)
{
*(temp1 + i) = '0';
}
temp1 = buf1;
len = len2;
}
for(i = 0; i < len; i++)
{
num = *(temp1 + i) + *(temp2 + i) + flag - 2 * '0';
flag = num / 10;
*temp3++ = num % 10 + '0';
}
if(flag > 0)
{
*temp3 = flag + '0';
temp3++;
flag = 0;
}
*temp3 = '\0';
printf("add1 + add2 = %s\n", strinv(dest));
return 0;
}
|