PAT Advanced 1001. A+B Format
PAT Advanced 1001. A+B Format
0. 写在前面:
没想到这么快就回来了(才不是因为C++ Primer, 5th太厚了doge),之前陆续看了一半的C++ Primer 5th,但真的看不动了。。。类的构造,模板这些真的顶不住,而且我确信如果继续看另一半,看完的这一半也会忘得差不多了QAQ。所以直接开刷PAT甲级,在实战中进步吧(我带了C++回来,但没完全带,不过先用一下vector,string这些库容器还是比C舒心不少的)。
PAT网址:https://www.patest.cn/practice
浙大出品的刷题网站,感觉比较适合打基础。另外附上大佬的博客:1001. A+B Format (20)-PAT甲级真题_1001 a+b format 柳诺_柳婼的博客-CSDN博客 ,PAT Basic 1001中推荐的大佬的网站好像崩了。。。
1. Problem Description:
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).
2. 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.
3. 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.
4. Sample Input:
-1000000 9
5. Sample Output:
-999,991
6. Performance Limit:
Code Size Limit
16 KB
Time Limit
400 ms
Memory Limit
64 MB
思路:
调用库函数to_string
将 \(a,b\) 的和转换为string类型并存入sum
,然后维护变量digitsCount
记录数字的个数,倒序遍历sum
,每满四个数字就在第三个和第四个数字间插入','
,这里插入调用的是string的成员函数insert()
,使用迭代器遍历string对象,把迭代器看作泛型指针即可。注意下digitsCount
递增到4后要被置为1而不是0,否则会造成计数错误。
参考大佬的题解:1001. A+B Format (20)-PAT甲级真题_1001 a+b format 柳诺_柳婼的博客-CSDN博客 ,判断条件(i + 1) % 3 == len % 3
的思路是很巧妙的,可以学习下。
My Code & Result:
#include <iostream>
#include <string> // string header
using namespace std;
int main(void)
{
int a=0, b=0;
string sum;
cin >> a >> b;
sum = to_string(a+b);
auto it_begin = sum.begin();
auto it_end = sum.end();
int digitsCount = 0;
while(it_end >= it_begin)
{
if(*it_end >= '0' && *it_end <= '9')
{
++digitsCount;
}
if(digitsCount == 4)
{
digitsCount = 1;
sum.insert(it_end+1, ',');
}
--it_end;
}
cout << sum << endl;
// cout << a << ' ' << b << endl;
return 0;
}
Compiler
C++ (g++)
Memory
464 / 65536 KB
Time
5 / 400 ms