写个博客来记录一下自己的甲级刷题,我会按每个知识点分类来刷题,每题会标注是什么类别的题目。
1001 A+B Format (20分)
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,b≤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
#include <iostream>
using namespace std;
int main(){
int a, b;
cin >> a >> b;
int c = a + b;
string sum = to_string(c);
string res;
for (int i = sum.size() - 1, j = 0; i >= 0; i--){
res = sum[i] + res;
j++;
if (j % 3 == 0 && sum[i - 1] != '-' && i != 0) res = ',' + res;
}
cout << res << endl;
return 0;
}
这题主要是考查字符串的处理,其中最主要用到的就是to_string()函数,这个函数可以将数字转换为字符串。转换成字符串后就很简单了,按题目给出的样例输出一下即可。
网友评论