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
给两个在[-1e6, 1e6]范围内的数字,计算a+b的值,结果每遇到3位前面打上一个逗号’,’,使其按照这个格式输出。
思路:模拟,利用stringstream容器直接将数字转成字符串。
#include <bits/stdc++.h>
using namespace std;
int a,b,res;
string itos(int res) {
stringstream s;
s << res;
return s.str();
}
int main() {
string ans;
cin >> a >> b;
res = a + b;
ans = itos(res);
int j = 1;
for (int i = ans.size() - 1; i > 0; i--, j++) {
if (j % 3 == 0 && (res >= 0 || res < 0 && i > 1)) {
ans.insert(i, 1, ',');
}
}
cout << ans << endl;
return 0;
}