PTA | 程序设计类实验辅助教学平台

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 . 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

solve

数字格式化输出类问题,要求从低位到高位每隔3个数加入逗号,数长小于4时不加。

字符串解法,a+b结果存为字符串,最终格式化输出另一个字符串

string formatedSum(long long sum) {
    string s = to_string(abs(sum));
    string result;
 
    if(sum < 0) result += "-";
    
    for(int i = 0; i < s.size(); i++) {
        if(i > 0 && (s.size() - i) % 3 == 0 ) result += ",";
        result += s[i];
    }
 
    return result;
}