大整数的加法

加法的步骤:

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

加法部分程序:

//高精度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;


}