大整数的加法

大整数的加法

加法的步骤:

    将该位上的两个数字与进位相加,得到的结果取个位数作为该位结果,取十位数作为新的进位。

加法部分程序:

//高精度a+b 
bign add(bign a,bign b)
{

    bign c;

    //carry是进位 
    int carry=0;

    //以较长的作为界限 

    for(int i=0;i<a.len|| i<b.len ;i++)
    {

        //两个对应位 以及 进位相加 
        int temp=a.d[i] + b.d[i] +carry;

        //个位数是该位的结果 
        c.d[c.len++] = temp %10;

        //十位数为新的进位
        carry = temp/10;




    }


    //如果最后进位不为0,则直接赋给结果的最高位 
    if(carry !=0 )
    {
        c.d[c.len++]=carry;


    }


    return c;






}


一个完整的应用程序:

#include <cstdio>
#include <cstdlib>
#include <iostream>
#include <algorithm>
#include <cmath>
#include <string>
#include <cstring>
#include <vector>



using namespace std;



struct bign{

    int d[1000];
    int len;

    bign()
    {
        fill(d,d+1000,0);
        len=0;


    }

};


bign change(string str)
{
    bign a;
    a.len=str.length();

    for(int i=0;i<a.len;i++)
    {
        a.d[i]=str[a.len-i-1]-'0';

    }

    return a;


}



bign add(bign a,bign b)
{
    bign c;

    int carry=0;

    for(int i=0;i<a.len||b.len ;i++)
    {
        int temp=a.d[i] + b.d[i] + carry;
        c.d[c.len++]=temp%10;
        carry = temp/10;

    }

    if( carry!=0)
    {
        c.d[c.len++]=carry;
    }


}


void print(bign a)
{
    for(int i=a.len-1;i>=0;i--)
    {
        printf("%d",a.d[i]);
    }

}

string str1,str2;

int main()
{



    cin>>str1>>str2;

    bign a=change(str1);
    bign b=change(str2);
    print(add(a,b));



    return 0;


}












  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值