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 −106≤a,b≤106. 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 <bits/stdc++.h>
using namespace std;
int main()
{
int a,b;
cin >> a >> b;
int sum = a+b;
if (sum < 0) {
cout << "-"; //先输出符号,后续只处理非负数
sum = -sum;
}
vector <char> v;
string s = to_string(sum); //添加‘,’ 把数字转化成字符串
int cnt = 0;
for (int i = s.size()-1; i >= 0; i--) {
cnt++;
v.push_back(s[i]); //cnt计数,满三个数字就加一个‘,’ 最后一个数字需要存进去用于输出,但不需要处理‘,’
if (cnt == 3 && i > 0) {
v.push_back(',');
cnt = 0;
}
}
for (int i = v.size()-1; i >= 0; i--) {
cout << v[i]; //输出
}
}