题目大意:计算整数A+B并输出,输出格式是每三个数用逗号分开,例如,-999991要输出为 -999,991。
字符串处理问题。先用 to_string 得到 A+B的字符串结果,然后定义一个空字符串,按每三个数字一组,从后向前复制原字符串,每三个数加逗号。最后倒序输出。
AC代码如下:
#include <iostream>
#include <vector>
#include <algorithm>
#include <cstdio>
#include <cmath>
#include <stack>
#include <queue>
#include <set>
#include <map>
#include <cstring>
using namespace std;
int main()
{
int a, b;
cin >> a >> b;
string str = to_string(a + b);
string ans;
for (int i = 0; i < str.size(); ++i)
{
char ch = str[str.size() - 1 - i];
if(i % 3 == 0 && i >= 3 && ch >= '0' && ch <= '9')
{
ans += ',';
ans += ch;
}
else ans += ch;
}
reverse(ans.begin(), ans.end());
printf("%s", ans.c_str());
return 0;
}