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
结尾无空行
题目大意
从后往前,每三位中间都要加上一个逗号。如果前面部分少于四位就不用。
比如1000,就是1,000。
10900就是10,900。
题目分析
因为懒得动脑所以动脑想了一个不用动脑的解决方法!!
首先因为怕麻烦所以先把-号给处理掉了。
然后倒序遍历数字,把遍历到的元素头插到output里去, 每隔3位插入一个,
然后输出output。
AC代码
#include <iostream>
#include <string>
#include <algorithm>
using namespace std;
int main()
{
int a, b, cnt = 0;
cin >> a >> b;
a += b;
string str = to_string(a), output = "";
int flag = 0;
if(str[0] == '-'){
flag = 1;
str = str.substr(1, str.size() - 1);
}
for (int i = str.size() - 1; i >= 0;i--){
if (cnt % 3 == 0&&(cnt>=3)) output += ',';
if(str[i]>='0'&&str[i]<='9') cnt++;
output += str[i];
}
if(flag)output += '-';
reverse(output.begin(), output.end());
cout << output;
}
总结
开始刷甲级了!