[PAT A1001]A+B Format
题目描述
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).
输入格式
Each input file contains one test case. Each case contains a pair of integers a and b where −106≤a,b≤106. The numbers are separated by a space.
输出格式
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.
输入样例
-1000000 9
输出样例
-999,991
解析
- 题目解释,输入两个数a,b,然后计算他们的和并以标准形式输出,就是按照从低到高每三位加一个逗号输出
- 根据题目给出的数的范围,我们可以使用两个int类型的变量去存储他们,而且保证不会溢出,具体实现过程见代码和注释
#include<iostream>
#include<string>
#include<algorithm>
using namespace std;
int main()
{
int a, b;
string str, ans;
cin >> a >> b;
a = a + b;
str = to_string(a); //数字转化为字符串
reverse(str.begin(), str.end()); //转置这个字符串
for (int i = 0; i < str.length(); i++) {
ans += str[i];
if ((i % 3 == 2) && (i + 1 < str.length()) && (str[i + 1] != '-')) ans += ',';
//如果某个地方该加逗号,我们必须判断它的下一位是不是超过了长度,以及它的下一位是不是‘-’号,这两种情况我们是不能加的
}
reverse(ans.begin(), ans.end()); //变回原来的格式
cout << ans;
return 0;
}