Luogu C++ Language | P1601 A+B Problem (High Precision)

Learn C++ from a young age! Record the questions asked during the Luogu C++ learning and exam preparation process, and record every moment.

Attached is a summary post: Luogu’s C++ language | Summary_The blog of a communicator who loves programming-CSDN blog


[Title description]

High-precision addition is equivalent to the a+b problem, without considering negative numbers .

【enter】

Enter in two lines. a , b ≤10^500.

【Output】

The output has only one line, representing  the value of a + b  .

【Input sample】

1001
9099

【Output sample】

10100

[Detailed code explanation]

#include <bits/stdc++.h>
using namespace std;
int aplusb(string a, string b, int *c) {
    int j1[505] = {0}, j2[505] = {0}, jw = 0;
    int lena = a.length(), lenb = b.length(), len=max(lena, lenb);
    //将字符串转成int数组并翻转
    for (int i=0; i<lena; i++) j1[i] = a[lena-i-1] - '0';
    for (int i=0; i<lenb; i++) j2[i] = b[lenb-i-1] - '0';
    //求和
    for (int i=0; i<len ; i++) {
        c[i] = j1[i] + j2[i] + jw;
        jw = c[i] / 10;
        c[i] = c[i] % 10;
    }
    if(jw > 0) {
        c[len] = jw;
        len++;
    }
    return len;
}
int main()
{
    string a, b;
    int c[505], n;
    cin >> a >> b;
    n = aplusb(a, b, c);
    for (int i=n-1; i>=0; i--) {
        cout << c[i];
    }
    return 0;
}

【operation result】

1001
9099
10100

Guess you like

Origin blog.csdn.net/guolianggsta/article/details/132904066