Example of high-precision addition operation
Enter the positive integers a and B, and output the value of a+b. 0<a,b<=10^250
Input:
First line: A
Second line: b
Output: A+b and.
Example input: 99
999
Sample output: 1098
Analysis: (1) addition operation ... a[7] a[6] a[5] a[4] a[3] a[2] a[1]
..... + ... 0 0 b[5] b[4] b[3] b[2] b[1]
——————————————————————————————————
... c[7] c[6] c[5] c[4] c[3] c[2] c[1]
Number of Operations =max (LA,LB)
(2) Program implementation: Method One: Simulate manual calculation, set a carry variable m
#include <iostream> #include <cstdio> #include <cstring>using namespace Std;char s1[300], S2[300];int A[300], b[300], C[300];int main () {int LA, LB, LC, m=0;cin >> s1 >> s2;la = strlen (s1); lb = strlen (s2); for (int i=1;i<=la;i++) A[i] = s1[la-i]-48;for (int i=1;i<=lb;i++) b[i] = s2[lb-i]-48;if (La > lb) lc = LA;ELSELC = Lb;for ( int i=1;i<=lc;i++) {C[i] = (m+a[i]+b[i])% 10;m = (M+a[i]+b[i])/10;} if (m==1) {LC++;C[LC] = 1;} for (int i=lc;i>=1;i--) cout << c[i];cout << endl;return 0;}
Method Two: Calculate first, and then handle the rounding
#include <iostream> #include <cstdio> #include <cstring>using namespace Std;char s1[300], S2[300];int A[300], b[300], C[300];int main () {int LA, lb, lc;cin >> s1 >> s2;la = strlen (s1); lb = strlen (s2); for (int i=1;i <=la;i++) A[i] = s1[la-i]-48;for (int i=1;i<=lb;i++) b[i] = s2[lb-i]-48;if (La > lb) lc = LA;ELSELC = lb;for (int i =1;i<=lc;i++) C[i] = a[i]+b[i];for (int i=1;i<=lc;i++) {c[i+1] = c[i+1] + c[i]/10;c[i] = c[i]% 10;} if (c[lc+1] = = 1) lc++;for (int i=lc;i>=1;i--) cout << c[i];cout << endl;return 0;}
High-precision Calculation (ii)/* High-precision addition operation */