序:
这是一道关于字符串处理的题。
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
题目概述:
把两数相加后的结果按照从后到前三位一个逗号的格式输出。
分析:
1.将int转为string方便处理
2.将原结果的str1从后往前遍历,每三个数位加一个’,’(注意首位不加),并将该结果写入str2
3.str2反转后即为所求
//从后到前加,
#include<bits/stdc++.h>
using namespace std;
int main()
{
int a, b;
scanf("%d%d", &a, &b);
int sum = a + b;
if(sum < 0) printf("-");
string str1 = to_string(abs(sum));
string str2;
for(int i = 0; i < str1.size(); i++)
{
str2 += str1[str1.size() - 1 - i];
if((i + 1) % 3 == 0 && i != str1.size() - 1) str2 += ',';
}
reverse(str2.begin(),str2.end());
printf("%s", str2.c_str());
printf("\n");
return 0;
}
总结:
这道题一开始debug了半天,通过测试样例发现原来我写的逗号是从前往后加的,直接傻了。。。所以,还是想清楚题目要求再编码!
续。2022.01.07代码:
#include<bits/stdc++.h>
using namespace std;
string format(int num) {
// 提取负号
bool isNegative = false;
if(num < 0) {
isNegative = true;
num = abs(num);
}
//反向找num
string res = "";
string mynum = to_string(num);
int cnt = 0;
//每三个加逗号
for(int i = mynum.size() - 1; i >= 0; i--) {
if(cnt % 3 != 0 || i == mynum.size() - 1)
res += mynum[i];
else {
res += ',';
res += mynum[i];
}
++cnt;
}
//反向结果
reverse(res.begin(), res.end());
//加负号
if (isNegative)
res = "-" + res;
return res;
}
int main() {
int a, b;
cin >> a >> b;
cout << format(a + b) << endl;
return 0;
}