吓了一跳哦

导航

C++算法之大数加法计算的代码

如下代码段是关于C++算法之大数加法计算的代码,希望对大家有用。

{
int length;
int index;
int smaller;
int prefix = 0;

if(NULL == src1 || 0 >= length1 || NULL == src2 || 0 >= length2)
return NULL;

length = length1 > length2 ? (length1 + 1) : (length2 + 1);
assert(NULL != dest);

smaller = (length2 < length1) ? length2 : length1;
for(index = 0; index < smaller; index ++)
dest[index] = src1[index] + src2[index];

if(length1 > length2){
for(; index < length1; index++)
dest[index] = src1[index];
}else{
for(; index < length2; index++)
dest[index] = src2[index];
}

for(index = 0; index < length; index ++){
dest[index] += prefix;
prefix = dest[index] / 10;
dest[index] %= 10;
}

return dest;
}





上面算法最大的特点就是:计算的时候没有考虑10进制,等到所有结果出来之后开始对每一位进行进制处理。讨论:看到上面的算法之后,大家可以考虑一下:(1)减法应该怎么写呢?(2)乘法呢?除法呢?




 

posted on 2019-04-16 10:38  吓了一跳哦  阅读(400)  评论(0编辑  收藏  举报