天天看點

pat甲級1001

1001 A+B Format (20 分)

Calculate a+b and output the sum in standard format – that is, the digits must be separated into groups of three by commas (unless there are less than four digits).

Input Specification:

Each input file contains one test case. Each case contains a pair of integers a and b where −10

6

≤a,b≤10

6

. The numbers are separated by a space.

Output Specification:

For each test case, you should output the sum of a and b in one line. The sum must be written in the standard format.

solution 1

#include <iostream>
using namespace std;
int idx[10];
int main()
{
    int a, b;
    cin >> a >> b;
    int c = a + b;
    if (c < 0)
        c = -c, cout << "-";
    int count = 0;
    do
    {
        idx[count++] = c % 10;
        c /= 10;
    } while (c);
    for (int i = count - 1; i >= 0; i--)
    {
        cout << idx[i];
        if (i % 3 == 0 && i)
            cout << ",";
    }
}
           

solution 2

#include <iostream>
#include <cstring>
using namespace std;
int main()
{
    int a, b;
    cin >> a >> b;
    int c = a + b;
    string d = to_string(c);
    for (int i = 0; d[i]; i++)
    {
        cout << d[i];
        if (d[i] == '-')
        {
            continue;
        }
        else
        {
            if ((i + 1) % 3 == d.size() % 3 && i != d.size() - 1)
                cout << ",";
        }
    }
}
           

繼續閱讀