A1001A+Bforamt

Posted pennyxia

tags:

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

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

思路:

判断sum正负,若为负输出-,然后将sum的绝对值存到字符串c中;遍历c,每三个元素且不是最后一个元素时输出逗号。

问题:

部分测试用例答案错误

解决:

从高位开始每三位加一个,这样最低一组可能不足三个,改成,从低位开始每三位一组。给出的样例太有迷惑性了…

 

 1 #include <iostream>
 2 #include <string>
 3 using namespace std;
 4 int main() {
 5     int a, b;
 6     cin >> a >> b;
 7     int sum = a + b;
 8     if (sum < 0)cout << "-";
 9     string c = to_string(abs(sum));
10     int len = c.length();
11     for (int i = 0; i < len; i++) {
12         cout << c [i];
13         if ((i+1) % 3 == len%3 &&i!=len-1)
14             cout << ",";
15     }
16     return 0;
17 }

 

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

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

1001. A+B Format (20)

Android代码片段

Android 实用代码片段

Android 实用代码片段

题目1001:A+B for Matrices