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
给出两个数字(-1000000
到1000000
之间),计算他们的和,以标准格式输出(形如 99,999,999
)
-1000000
到1000000
之间,所以直接用int
保存求和即可,不会溢出
to_string()
是c++11引入的新方法)
'-'
','
,标准格式是从后往前三个一输出,假设转成字符串后的长度为len
,那么 len % 3
就是最前面多出的长度,也就是第一个 ','
出现的位置,后面的都可以三个一组,就隔三个,输出一个 ','
。
比如 12,345,666
,len = 8
, len % 3 = 2
,所以第2个数字后面加 ','
,第5个数字后面加 ',',第 8 个数字后加 ',',但是第8个是最后一个数字,所以要排除。所以 条件就是 i % 3 == len % 3
,但是因为我们的下标是从0开始的,而我们是数数字个数判断,所以应该是 (i + 1) % 3 == len % 3 && (i != len % 3)
#include <iostream>
using namespace std;
int main() {
int a, b;
cin >> a >> b;
// 两数和转为字符串
string s = to_string(a + b);
// 得到有效长度
int len = s.length();
for (int i = 0; i < len; i++) {
// 输出当前位
cout << s[i];
if (s[i] == '-')
continue;
// 标准化格式 -xx,123,999
if ((i + 1) % 3 == len % 3 && i != len - 1)
cout << ",";
}
return 0;
}