原题:https://pintia.cn/problem-sets/994805342720868352/problems
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
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
题目分析:
风格一:
先计算A+B的和,然后利用to_string
转成字符串;除了第一位是负号的情况,只要当前下标满足(len-1-i)%3==0
即,剩下的位数是3的倍数的时候,且i不是最后一位,就在逐位输出后加上一个逗号。
#include <iostream>
#include <string>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
int res = a + b;
string ans = to_string(res);
for (int i = 0; i < ans.length(); i++) {
cout << ans[i];
if (ans[i] == '-') continue;// 负数不能考虑第一符号位
//if ((i + 1) % 3 == ans.length() % 3 && i != ans.length() - 1)
if ((ans.length() - 1 - i) % 3 == 0 && i != ans.length() - 1)
cout << ",";
}
cout << endl;
system("pause");
return 0;
}