Skip to content

1001 A+B Format

Statement

Metadata

  • 作者: CHEN, Yue
  • 单位: 浙江大学
  • 代码长度限制: 16 KB
  • 时间限制: 400 ms
  • 内存限制: 64 MB

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 \le a, b \le 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.

Sample Input

-1000000 9

Sample Output

-999,991

Solution

#include <bits/stdc++.h>
using namespace std;
void tran(int x) {
    string s1 = "", s2 = "";
    int i, j, flag = 0;
    if (x) {
        if (x < 0)
            flag = 1, x *= -1;
        while (x) {
            s1 += x % 10 + '0';
            x /= 10;
        }
        int len1 = s1.size();
        if (len1 >= 4) {
            for (i = 0; i < len1; i++) {
                if (i % 3 == 0 && i)
                    s2 += ",";
                s2 += s1[i];
            }
        } else
            s2 = s1;
        if (flag)
            cout << "-";
        int len2 = s2.size();
        for (i = len2 - 1; i >= 0; i--) cout << s2[i];
    } else
        cout << "0";
    cout << "\n";
}
int main() {
    int a, b;
    cin >> a >> b;
    a += b;
    tran(a);
}

Last update: May 4, 2022
Back to top