This article is participating in the nuggets team number online activity, click to see the dachang spring recruiting positions
1. Title Description
Take two integers A and b and print the sum of the two integers. Neither a nor B has more than 100 digits. Algorithm description Because both A and B are large, they cannot be stored directly using standard data types in the language. For this kind of problem, you usually use arrays. Define an array A, where A[0] is used to store the ones bits of A, A[1] is used to store the tens of A, and so on. You can also use an array B to store B. To calculate c = a + b, first add a [0] and b [0]. If there is a carry, store the carry (the tens of the sum) in R and the units of the sum in C[0], that is, c [0] is equal to (a [0]+ b [0])%10. Then add A[1] and B[1], then add up the low value r, that is, C[1] should be the sum of A[1], B[1] and R. If more carry is generated, the new carry can still be stored in r, and the bits of and in C[1]. And so on, we can figure out all the bits of C. Finally, output C. Input format The input consists of two lines. The first line is a non-negative integer A and the second line is a non-negative integer b. Neither integer has more than 100 digits, and the highest digit in both numbers is not 0. Output format The output line represents the value of a + b. The sample input sample output 20100122203011233454668012 2010012220100122 20100122201001221234567890
Second, train of thought analysis
You input the data as a string, you put it in reverse order into an array and then you simulate adding it up bit by bit to see if the highest bit changes before you output it
AC code
#include<bits/stdc++.h>
using namespace std;
int main()
{
string a,b;
int A[100] = {0},B[100] = {0},C[101] = {0};
cin>>a>>b;
int lena=a.length(),lenb=b.length(),lenc;
int k=0;
for(int i=lena-1; i>=0; i--) A[k++]=a[i]-'0';
k=0;
for(int i=lenb-1; i>=0; i--) B[k++]=b[i]-'0';
int t=0;
for(int i=0; i<100; i++) { C[i]=A[i]+B[i]+t; t=C[i]/10;
C[i]=C[i]%10;
}
if(lena>lenb)
lenc=lena;
else
lenc=lenb;
if(C[lenc]! =0)
lenc++;
for(int i=lenc-1; i>=0; i--) cout<<C[i];return 0;
}
Copy the code
Method 2
#include<bits/stdc++.h>
using namespace std;
int main()
{
string a,b;
int A[101] = {0},B[101] = {0};
cin>>a>>b;
int lena=a.length(),lenb=b.length(),len;
if(lena>lenb)
len=lena;
else
len=lenb;
int k=0;
for(int i=lena-1; i>=0; i--) A[k++]=a[i]-'0';
k=0;
for(int i=lenb-1; i>=0; i--) B[k++]=b[i]-'0';
for(int i=0; i<len; i++) { A[i]=A[i]+B[i]; A[i+1]+=A[i]/10;
A[i]=A[i]%10;
}
if(A[len]! =0)
len++;
for(int i=len-1; i>=0; i--) cout<<A[i];return 0;
}
Copy the code
Four,
Brush, brush, brush can’t waste the weekend