1001 A+B Format (20 分)
1. 题目
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
2. 题意
将两个数a和b相加,并按照从低位到高位,三位一逗号形式输出。
3. 思路——简单模拟
- a和b相加后以字符串形式存储,从字符串尾部开始遍历,每三位插入一个逗号。
- 边界条件:
- 位数刚为3的倍数时:例123,此时遍历到1时,计数cnt刚好为3,但是因为i为0,所以条件不满足,不会插入新的逗号。
- 负数:例-123,此时遍历到1时,计数刚好为3,虽然此时i为1,但是判断sum[i - 1]为负号,不满足条件,不会插入新的逗号。
4. 代码
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
string sum = to_string(a + b);
int cnt = 0; // 计数每三位需添加一个逗号
for (int i = sum.size() - 1; i >= 0; --i)
{
cnt++;
// 这里中间的条件为i不为0,防止sum[i-1]溢出
if (cnt % 3 == 0 && i && sum[i - 1] != '-')
{
sum.insert(i, 1, ','); // 满足三位一个逗号,并将逗号插入
cnt = 0; // 插入逗号后,计数清零
}
}
cout << sum <<endl;
return 0;
}