找回密碼
 立即注冊

QQ登錄

只需一步,快速開始

搜索
查看: 3383|回復: 0
打印 上一主題 下一主題
收起左側(cè)

實現(xiàn)兩個大數(shù)(64位)相加函數(shù)簡單實現(xiàn)

[復制鏈接]
跳轉(zhuǎn)到指定樓層
樓主
ID:51090 發(fā)表于 2014-9-24 22:19 | 只看該作者 回帖獎勵 |倒序瀏覽 |閱讀模式
本帖最后由 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;
}



分享到:  QQ好友和群QQ好友和群 QQ空間QQ空間 騰訊微博騰訊微博 騰訊朋友騰訊朋友
收藏收藏 分享淘帖 頂 踩
回復

使用道具 舉報

您需要登錄后才可以回帖 登錄 | 立即注冊

本版積分規(guī)則

手機版|小黑屋|51黑電子論壇 |51黑電子論壇6群 QQ 管理員QQ:125739409;技術(shù)交流QQ群281945664

Powered by 單片機教程網(wǎng)

快速回復 返回頂部 返回列表