C ++ precision adder

Precision adder

Problem Description
input two integers a and b, and outputs of the two integers. a and b are not more than 100.
Algorithmic descriptions
since a and b are relatively large, can not be used directly in the standard data types of stored language. For this problem, generally use an array to handle.
Define an array A, A [0] is used to store a bit, A [1] for storing a ten, and so on. B can also be used to store an array b.
C = a + b is calculated when the first A [0] and B [0] are added, if there is carry, carry put (i.e., the tens and) into r, and the existence of the single-digit the C [0], i.e., C [0] is equal to (A [0] + B [ 0])% 10. Then calculates A [1] and B [1] are added, then the feed should also be low also add up the value r, i.e., C [1] should be A [1], B [1] and three number r and. If there carry generation, you may still carry the new stored into the r, and stored into the bit C [1] in. And so on, you can find all the bits C.
Finally, the C output can be.
Input format
input comprises two rows, a first row of non-negative integers a, a second line non-negative integer b. Two integers no more than 100, the highest two-bit number is not zero.
Output format
output line, represents the value of a + b.
Sample input
20100122201001221234567890
2010012220100122
Sample Output
20100122203011233454668012

    #include<iostream>
    #include<stdio.h>
    #include<string.h>
    using namespace std;
    int main()
    {
        int i,r=0,max,lena,lenb;
        char s1[100],s2[100];
        int a[100],b[100];
        gets(s1);gets(s2);
        lena=strlen(s1);lenb=strlen(s2);
        for(i=0;i<lena;i++) a[i]=s1[lena-i-1]-'0';
        for(i=0;i<lenb;i++) b[i]=s2[lenb-i-1]-'0';//将s1,s2分别倒序赋给a,b(高精度加法是从末位开始往前加)
        if(lena>=lenb) max=lena;
        else max=lenb;
        if(lena>lenb) for(i=lenb;i<lena;i++) b[i]=0;
        if(lena<lenb) for(i=lena;i<lenb;i++) a[i]=0;//当a,b位数不同时,给位数少的赋0,保证后面的运算
        int c[102];
        for(i=0;i<max;i++)
        {   c[i]=r+a[i]+b[i];
            r=c[i]/10;
            c[i]=c[i]%10;     
        }
        while(r!=0)
         {max++;
         c[max-1]=r%10;
         r=r/10;    
        }
        for(i=max-1;i>=0;i--)  cout<<c[i];
        cout<<endl;
    return 0;
    }

To fully consider!

[Recommended] can look at this entry-precision algorithm [] (https://blog.csdn.net/zsjzliziyang/article/details/82050337)

 

 

Guess you like

Origin blog.csdn.net/qq_42458302/article/details/87926563