1001 A+B Format

Posted menglingxin

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了1001 A+B Format相关的知识,希望对你有一定的参考价值。

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,b10?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


题意:给出a和b两个数,计算出其和后,按照从后向前的顺序每三个数之前加一个逗号,最后输出这个数和添加的逗号,如果该数为负,要输出负号。

分析:本题将数字转化成字符串可以减少很多麻烦,先判断该数正负,如果为负则输出负号,利用to_string()函数将数的绝对值转化成字符串。加逗号时,要注意数组下标应该+1,(i+1)% 3要等于length % 3,并且不能在最后添加逗号。

AC code:
#include<iostream>
#include<string>
using namespace std;
int main(void)
{
    long long a, b, c;
    cin >> a >> b;
    if (a + b < 0) cout << "-";
    string str = to_string(abs(a + b));
    for (int i = 0; i < str.length(); ++i) {
        cout << str[i];
        if ((i + 1) % 3 == str.length() % 3 &&
            i != str.length() - 1) cout << ",";
    }
    return 0;
}

 

以上是关于1001 A+B Format的主要内容,如果未能解决你的问题,请参考以下文章

PAT甲级 1001. A+B Format (20)

1001A+B Format

1001 A+B Format

PAT甲级(1001:A+B Format)

1001 A+B Format

PAT 1001 A+B Format